이 gem은 ActiveModel
기반으로 구축되어 직접 구현할 필요 없이 Rails에서 모델로 유효성 검사, 이름 지정 및 i18n
가져올 수 있는 방법을 보여줍니다.
이 README는 Rails 5+에서 사용되는 MailForm gem을 참조합니다. 이전 버전의 Rails에서 MailForm을 사용하는 방법에 대한 지침은 사용 가능한 브랜치를 참조하세요.
MailForm을 사용하면 양식에서 직접 이메일을 보낼 수 있습니다. 예를 들어 문의 양식을 만들려면 다음 줄만 있으면 됩니다(이메일 포함).
class ContactForm < MailForm :: Base
attribute :name , validate : true
attribute :email , validate : / A [^@ s ]+@[^@ s ]+ z /i
attribute :file , attachment : true
attribute :message
attribute :nickname , captcha : true
# Declare the e-mail headers. It accepts anything the mail method
# in ActionMailer accepts.
def headers
{
subject : "My Contact Form" ,
to : "[email protected]" ,
from : %(" #{ name } " < #{ email } >)
}
end
end
그런 다음 rails console
로 콘솔을 시작하고 다음을 입력합니다.
>> c = ContactForm . new ( name : 'José' , email : '[email protected]' , message : 'Cool!' )
>> c . deliver
받은 편지함을 확인하면 보낸 필드와 함께 이메일이 있을 것입니다(메일러 전달 방법을 올바르게 구성했다고 가정).
MailForm::Base
에서 상속하면 ActiveModel::Validation
, ActiveModel::Translation
및 ActiveModel::Naming
과 같은 항목 집합을 ActiveModel
에서 가져옵니다.
이로 인해 I18n
, 오류 메시지, 검증 및 ActiveRecord
와 같은 속성 처리가 MailForm 으로 제공되므로 추가 조정 없이 컨트롤러 및 양식 빌더에서 MailForm을 사용할 수 있습니다. 이는 또한 다음 대신에 다음을 의미합니다.
attribute :email , validate : / A [^@ s ]+@[^@ s ]+ z /i
실제로 다음과 같이 할 수 있습니다.
attribute :email
validates_format_of :email , with : / A [^@ s ]+@[^@ s ]+ z /i
가장 마음에 드는 것을 선택하세요. API에 대한 자세한 내용을 보려면 아래를 계속 읽어보세요.
MailForm은 ORM과도 잘 작동합니다. 모델에 MailForm::Delivery
포함하고 어떤 속성을 보내야 하는지 선언하면 됩니다.
class User < ActiveRecord :: Base
include MailForm :: Delivery
append :remote_ip , :user_agent , :session
attributes :name , :email , :created_at
def headers
{
to : "[email protected]" ,
subject : "User created an account"
}
end
end
전달은 after_create
후크에서 트리거됩니다.
MailForm을 설치하는 것은 매우 쉽습니다. 다음을 추가하여 Gemfile을 편집하세요.
gem 'mail_form'
그런 다음 bundle install
실행하여 MailForm을 설치합니다.
rails generate mail_form
실행하여 시작하는 데 필요한 기본 양식을 생성하는 방법에 대한 도움말 정보를 볼 수 있습니다.
양식 속성을 선언합니다. 여기에 선언된 모든 속성은 :captcha가 true인 속성을 제외하고 이메일에 추가됩니다.
옵션:
:validate
- validates_*_of
대한 후크입니다. true
제공되면 속성의 존재 여부를 확인합니다. 정규식인 경우 형식의 유효성을 검사합니다. 배열인 경우 배열에 속성이 포함되어 있는지 확인합니다.
:validate
주어질 때마다 자동으로 존재 여부를 확인합니다. 재정의하려면 allow_blank: true
지정하세요.
마지막으로 :validate
기호인 경우 기호로 지정된 메서드가 호출됩니다. 그런 다음 Active Record( errors.add
)에서와 마찬가지로 유효성 검사를 추가할 수 있습니다.
:attachment
- 주어지면 파일이 전송될 것으로 예상하고 이를 이메일에 첨부합니다. 양식을 다중 유형으로 설정하는 것을 잊지 마십시오. 또한 단일 첨부 속성을 통해 여러 파일을 허용하고 개별적으로 이메일에 첨부합니다.
:captcha
- true인 경우 속성이 비어 있어야 하는지 확인합니다. 이는 스팸을 방지하는 간단한 방법이며 CSS를 사용하여 입력을 숨겨야 합니다.
예:
class ContactForm < MailForm :: Base
attributes :name , validate : true
attributes :email , validate : / A [^@ s ]+@[^@ s ]+ z /i
attributes :type , validate : [ "General" , "Interface bug" ]
attributes :message
attributes :screenshot , attachment : true , validate : :interface_bug?
attributes :nickname , captcha : true
def interface_bug?
if type == 'Interface bug' && screenshot . nil?
self . errors . add ( :screenshot , "can't be blank on interface bugs" )
end
end
end
c = ContactForm . new ( nickname : 'not_blank' , email : '[email protected]' , name : 'José' )
c . valid? #=> true
c . spam? #=> true (raises an error in development, to remember you to hide it)
c . deliver #=> false (just delivers if is not a spam and is valid, raises an error in development)
c = ContactForm . new ( email : 'invalid' )
c . valid? #=> false
c . errors . inspect #=> { name: :blank, email: :invalid }
c . errors . full_messages #=> [ "Name can't be blank", "Email is invalid" ]
c = ContactForm . new ( name : 'José' , email : '[email protected]' )
c . deliver
또한 MailForm을 사용 하면 클라이언트의 요청 정보를 보낸 메일에 쉽게 추가할 수 있습니다. 당신은 다음을 수행해야합니다 :
class ContactForm < MailForm :: Base
append :remote_ip , :user_agent , :session
# ...
end
그리고 컨트롤러에서:
@contact_form = ContactForm . new ( params [ :contact_form ] )
@contact_form . request = request
원격 IP, 사용자 에이전트 및 세션은 요청 정보 세션에서 이메일로 전송됩니다. 요청 객체가 응답하는 모든 메소드를 추가하도록 제공할 수 있습니다.
MailForm 의 I18n은 ActiveRecord와 마찬가지로 작동하므로 모든 모델, 속성 및 메시지를 현지화하여 사용할 수 있습니다. 다음은 I18n 파일 예제 파일입니다.
mail_form :
models :
contact_form : "Your site contact form"
attributes :
contact_form :
email : "E-mail"
telephone : "Telephone number"
message : "Sent message"
request :
title : "Technical information about the user"
remote_ip : "IP Address"
user_agent : "Browser"
사용되는 이메일 템플릿을 사용자 정의하려면 app/views/mail_form
에 contact.erb
라는 파일을 생성하세요. 기본 템플릿이 어떻게 작동하는지 보려면 이 저장소의 lib/mail_form/views/mail_form/contact.erb
를 살펴보세요.
우리는 아직 지원이 종료되지 않은 모든 Ruby/Rails 버전에 대한 지원을 유지할 계획입니다.
특정 버전에 대한 자세한 내용은 Ruby 및 Rails 유지 관리 정책과 테스트 매트릭스를 확인하세요.
버그를 발견한 경우 github 문제 추적기를 사용하세요.
MIT 라이센스. 저작권 2020-2024 Rafael França, Carlos Antônio da Silva. 저작권 2009-2019 Plataformatec.