class Attachs::Builder

Attributes

concern[R]
model[R]

Public Class Methods

new(model) click to toggle source
# File lib/attachs/builder.rb, line 6
def initialize(model)
  @model = model
  @concern = Module.new do
    extend ActiveSupport::Concern
    include Concern
  end
end

Public Instance Methods

define(attribute, options={}) click to toggle source
# File lib/attachs/builder.rb, line 14
def define(attribute, options={})
  unless options.has_key?(:path)
    raise 'Path required'
  end
  define_writer attribute
  define_reader attribute, options
  define_attributes_writer attribute, options
  model.include concern
  model.attachments[attribute] = options
end

Private Instance Methods

define_attributes_writer(attribute, options) click to toggle source
# File lib/attachs/builder.rb, line 56
def define_attributes_writer(attribute, options)
  concern.class_eval do
    define_method "#{attribute}_attributes=" do |collection_or_attributes|
      if options[:multiple]
        collection_or_attributes.each do |attributes|
          if id = attributes.delete(:id)
            attachment = send(attribute).find(id)
          else
            attachment = send(attribute).new
          end
          attributes.each do |name, value|
            attachment.send "#{name}=", value
          end
        end
      else
        collection_or_attributes.each do |name, value|
          send(attribute).send "#{name}=", value
        end
      end
    end
  end
end
define_reader(attribute, options) click to toggle source
Calls superclass method
# File lib/attachs/builder.rb, line 35
def define_reader(attribute, options)
  concern.class_eval do
    define_method attribute do
      variable = "@#{attribute}"
      if instance = instance_variable_get(variable)
        instance
      else
        if options[:multiple]
          klass = Attachs::Collection
        else
          klass = Attachs::Attachment
        end
        instance_variable_set(
          variable,
          klass.new(self, attribute, options, super())
        )
      end
    end
  end
end
define_writer(attribute) click to toggle source
# File lib/attachs/builder.rb, line 27
def define_writer(attribute)
  concern.class_eval do
    define_method "#{attribute}=" do |value|
      send(attribute).assign value
    end
  end
end