Sha256: 4748d26b0384f9885d0bac3ae7a35e326484902ddffbee8d64b1d3be57c120fd

Contents?: true

Size: 1.36 KB

Versions: 3

Compression:

Stored size: 1.36 KB

Contents

module AttributeExtras
  class HookBuilder

    # store the given options
    def initialize(verb, past)
      @verb = verb
      @past = past
    end

    # build the hook
    def build
      hook = Module.new
      hook.module_eval(module_definition)
      hook
    end

    private

      # the module definition for the extra
      def module_definition
        <<-RUBY
          def #{@verb}_attributes(*attributes, validator: true, writer: true)
            if self.table_exists? && (non_attributes = attributes.map(&:to_s) - self.column_names).any?
              raise ArgumentError, "Invalid attributes passed to #{@verb}_attributes: \#{non_attributes.join(', ')}"
            end

            include ::AttributeExtras::#{@verb.capitalize}Attributes

            attributes.each do |attribute|
              options = self.#{@verb}_options_for(attribute)
              modifier = Modifier.new(attribute, options)

              if validator
                validates attribute, self.#{@verb}_validator_for(modifier.options)
              end

              if writer
                define_method("\#{attribute}=") do |value|
                  write_attribute(attribute, self.class.#{@verb}_attribute_extra(value, modifier.options))
                end
              end

              #{@past}_attributes << modifier
            end
          end
        RUBY
      end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
attribute_extras-0.1.2 lib/attribute_extras/hook_builder.rb
attribute_extras-0.1.1 lib/attribute_extras/hook_builder.rb
attribute_extras-0.1.0 lib/attribute_extras/hook_builder.rb