Sha256: 98ae72dd23cf9ab977d2140c90c9c2d537983390c9e3719940e9ed84a3539be1

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

module HasOptionsHash
  module HasOptions
    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods
      def has_options(options={})
        configuration = { :option_model => "Option", :association_name => :options}
        configuration.update(options) if options.is_a?(Hash)
        
        association_name = configuration[:association_name].to_s
        singular_association = association_name.singularize
        option_model = configuration[:option_model]
        table_name = option_model.constantize.table_name
        has_many association_name, :class_name => configuration[:option_model], :as => :entity, :dependent => :destroy, :conditions => {:association_type => association_name}
        
        class_eval <<-EOV
          define_method "find_#{singular_association}_value" do |name|
            (opt = association_name.find_by_name(name.to_s)) ? opt.value : nil    
          end

          define_method "find_#{singular_association}_values" do |name|
            association_name.find_all_by_name(name.to_s).collect(&:value)
          end

          define_method "#{association_name}_hash" do
            option_hash = Hash.new {|h,k| h[k] = []}

            association_name.each do |option|
              option_hash[k] << option.value.to_s
            end

            option_hash
          end
        EOV

      end
    end
      
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
has_options-0.2.0 lib/has_options/has_options.rb