Sha256: cce24ce19ff3a0730a92235b66720ebebaccac81f3675168d04a904eb74d8e82

Contents?: true

Size: 1.18 KB

Versions: 7

Compression:

Stored size: 1.18 KB

Contents

require 'active_support/concern'

module NamedSeeds
  module Read
    
    extend ActiveSupport::Concern
    
    module ClassMethods

      def named_seeds(name, options = {})
        klass = options[:klass] || name.to_s.classify.constantize
        identities = options[:identities]
        case identities
        when Hash
          define_method(name) do |*fixnames|
            objs = fixnames.map do |fixname|
              id = identities[fixname.to_sym]
              find_named_seed name, klass, id, fixname
            end
            fixnames.one? ? objs.first : objs
          end
        else
          define_method(name) do |*fixnames|
            objs = fixnames.map do |fixname|
              id = NamedSeeds.identify(fixname)
              find_named_seed name, klass, id, fixname
            end
            fixnames.one? ? objs.first : objs
          end
        end
      end
        
    end

    protected
    
    def find_named_seed(name, klass, id, fixname)
      begin
        klass.find(id)
      rescue ActiveRecord::RecordNotFound => e
        nsfinder = :"#{name}_#{fixname}"
        raise e unless respond_to?(nsfinder)
        send(nsfinder)
      end
    end
    
  
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
named_seeds-1.1.0 lib/named_seeds/read.rb
named_seeds-1.0.5 lib/named_seeds/read.rb
named_seeds-1.0.4 lib/named_seeds/read.rb
named_seeds-1.0.3 lib/named_seeds/read.rb
named_seeds-1.0.2 lib/named_seeds/read.rb
named_seeds-1.0.1 lib/named_seeds/read.rb
named_seeds-1.0.0 lib/named_seeds/read.rb