Sha256: 6e2f1a7beccb6314e20eafe9554c9e2ad2ab51e02f2f1ab5ccd281bc89d30a39

Contents?: true

Size: 1.38 KB

Versions: 20

Compression:

Stored size: 1.38 KB

Contents

require 'active_support/concern'

module Journey::Resource::EnumSets
  extend ActiveSupport::Concern

  included do
    def self.enum_set(attr, collection=[])
      (@enum_sets ||= []) << attr

      collection_const_name = attr.to_s.pluralize.upcase.to_sym
      const_set collection_const_name, collection.freeze

      define_method "#{attr}_values" do
        self.class.const_get(collection_const_name)
      end

      define_method attr do
        arr = attributes[attr.to_s].presence || []
        arr.map do |member|
          if member.is_a?(Fixnum)
            self.class.const_get(collection_const_name)[member]
          else
            member
          end
        end
      end

      define_method "#{attr}=" do |value|
        attributes[attr.to_s] = value.map do |member|
          if member.is_a?(Fixnum)
            member
          else
            self.class.const_get(collection_const_name).index(member)
          end
        end 
      end

      define_method "add_#{attr}" do |value|
        attr_values = send("#{attr}_values")

        value_index = if value.is_a?(Fixnum)
          value
        else
          attr_values.index(value)
        end

        if (0..attr_values.size-1).include? value_index
          (attributes[attr.to_s] ||= []) << value_index
        else
          raise "Invalid enum_set value: '#{value}' for '#{attr}'"
        end
      end
    end

  end

end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
embark-journey-0.1.8 lib/journey/resource/enum_sets.rb
embark-journey-0.1.7 lib/journey/resource/enum_sets.rb
embark-journey-0.1.6 lib/journey/resource/enum_sets.rb
embark-journey-0.1.5 lib/journey/resource/enum_sets.rb
embark-journey-0.1.4 lib/journey/resource/enum_sets.rb
embark-journey-0.1.3 lib/journey/resource/enum_sets.rb
embark-journey-0.1.1 lib/journey/resource/enum_sets.rb
embark-journey-0.1.0 lib/journey/resource/enum_sets.rb
embark-journey-0.0.29 lib/journey/resource/enum_sets.rb
embark-journey-0.0.28 lib/journey/resource/enum_sets.rb
embark-journey-0.0.27 lib/journey/resource/enum_sets.rb
embark-journey-0.0.26 lib/journey/resource/enum_sets.rb
embark-journey-0.0.25 lib/journey/resource/enum_sets.rb
embark-journey-0.0.24 lib/journey/resource/enum_sets.rb
embark-journey-0.0.23 lib/journey/resource/enum_sets.rb
embark-journey-0.0.22 lib/journey/resource/enum_sets.rb
embark-journey-0.0.21 lib/journey/resource/enum_sets.rb
embark-journey-0.0.20 lib/journey/resource/enum_sets.rb
embark-journey-0.0.19 lib/journey/resource/enum_sets.rb
embark-journey-0.0.18 lib/journey/resource/enum_sets.rb