Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ActiveModel::Niceties

cfcosta
September 14, 2012

 ActiveModel::Niceties

My presentation at Codeminer 42 Tech Talk on 08/28/2012

cfcosta

September 14, 2012
Tweet

Other Decks in Technology

Transcript

  1. <%= form_for @contact do |f| %> <%= f.label :name %>

    <%= f.text_field :name %> <%= f.label :email %> <%= f.text_field :email %> <%= f.label :body %> <%= f.text_area :body %> <%= f.submit %> <% end %> Tuesday, August 28, 12
  2. class ContactController < ApplicationController def new @contact = Contact.new end

    def create @contact = Contact.new(params[:contact]) if @contact.valid? # Code to send the contact mail else render 'new' end end end Tuesday, August 28, 12
  3. class ContactForm extend ActiveModel::Naming include ActiveModel::Conversion attr_accessor :name, :email, :body

    def initialize(attributes = {}) attributes.each_pair do |k,v| send(:”#{k}=”, v) end end def persisted? false end end Tuesday, August 28, 12
  4. FactoryGirl.define do factory :contact_form do name { Faker::Name.name } email

    { Faker::Internet.email } body { Faker::Lorem.paragraphs(3).join("\n") } end end But some tests first... Tuesday, August 28, 12
  5. require 'spec_helper' describe Contact do subject { build :contact }

    it "is valid with valid attributes" do should be_valid end it "is not valid without name" do subject.name = nil should_not be_valid end it "is not valid without (or with invalid) email" do subject.email = nil should_not be_valid subject.email = "invalid email" should_not be_valid end it "is not valid without body" do subject.body = nil should_not be_valid end end Tuesday, August 28, 12
  6. class Contact extend ActiveModel::Naming include ActiveModel::Conversion include ActiveModel::Validations attr_accessor :name,

    :email, :subject, :body validates :name, :email, :body, presence: true validates :email, format: { with: %r{.+@.+\..+} }, allow_blank: true def initialize(attributes = {}) attributes.each do |k, v| send("#{k}=", v) end end def persisted? false end end Tuesday, August 28, 12
  7. Does it work? You can bet your sorry ass that

    it does. Tuesday, August 28, 12
  8. class ContactsController < ApplicationController include ActiveModel::MassAssignmentSecurity attr_accessible :name, :email, :password

    # #new removed for briefness def create @contact = Contact.new(contact_params) if @contact.valid? # blabla else render 'new' end end private def contact_params params[:contact] ||= {} sanitize_for_mass_assignment(params[:contact]) end end Tuesday, August 28, 12
  9. What about roles? def contact_params role = current_user.admin? ? :user

    : :admin params[:contact] ||= {} sanitize_for_mass_assignment(params[:contact], as: role) end Tuesday, August 28, 12
  10. Rails have a lot of things ready for use. Just

    use them. Tuesday, August 28, 12