11

weekly learning

Posted by ilake on October 15, 2016

“strive 10/9 ~ 10/15”

Use

Read

Book

  • [rails] Crafting Rails 4 Applications

    • chapter2: Building Models with Active Model
      • Adding Attribute Methods
        • include ActiveModel::AttributeMethods 1) attribute methods behavior
        • attribute_method_prefix 'clear_' 2) clear_ is attribute prefix
        • define_attribute_methods(names) 3) Ask to define the prefix methods for the given attribute names
        • def clear_attribute(attribute) 4) Since we declared a “clear_” prefix, it expects to have a “clear_attribute” method defined, which receives an attributen ame and implements the clearing logic.
      • Aiming for an Active Model–Compliant API
        • include ActiveModel::Conversion
          • to_key(), to_param(), and to_partial_path()
        • extend ActiveModel::Naming
          • human(), singular()
        • extend ActiveModel::Translation
          • i18n
      • Delivering the Form
        • class_attribute :attribute_names
        • self.attribute_names = [] 1) Define a class attribute and initialize it
        • self.attribute_names += names 2) Add new names as they are defined
      • initialize set value

        def initialize(attributes = {})ttributes.each do |attr, value|
          self.public_send("#{attr}=", value)
          end if attributes
        end
        
      • Validators
        • validates_presence_of
        def validates_presence_of(*attr_names)
          validates_with PresenceValidator, _merge_attributes(attr_names)
        end
        

        const_get("#{key.to_s.camelize}Validator")

        • ActiveModel::EachValidator
        class AbsenceValidator < ActiveModel::EachValidator
          def validate_each(record, attribute, value)
            record.errors.add(attribute, :invalid, options) unless value.blank?
          end
        end
        
      • Callbacks
        • extend ActiveModel::Callbacks 1) Add callbacks behavior
        • define_model_callbacks :deliver 2) Define the callbacks. The line below will create both before_deliver, and after_deliver callbacks with the same semantics as in Active Record
        • run_callbacks(:deliver) {} Change deliver to run the callbacks