Sha256: b0fb0bc88d91a2b2d24d636ebe35fdb53599fe541c2fcd4cabaa37c2f84ce53a

Contents?: true

Size: 1.54 KB

Versions: 26

Compression:

Stored size: 1.54 KB

Contents

module Eco
  module API
    module Common
      # Helpers for dynammic generation of classes based on a hierarchical model
      # @attr_reader model [Hash, nil] the `model` of the current `class`
      module ClassHierarchy
        include Eco::API::Common::ClassHelpers

        attr_reader :model

        # @param value [Hash, Enumerable, String, Symbol, nil] unparsed model to be assigned to the `class`
        def model=(value)
          @model = parse_model(value)
        end

        # @return [Array<String>] the `keys` of the current class' `model`
        def model_attrs
          (model && model.keys) || []
        end

        # Thanks to this step the format on the declaration of the model is flexible
        # @param value [Hash, Enumerable, String, Symbol, nil]
        # @return [Hash, nil] where keys are `Symbol` s
        def parse_model(model)
          case model
          when String
            return parse_model(model.to_sym)
          when Symbol
            return {model => nil}
          when Hash
            return model.each_with_object({}) do |(k,v), hash|
              hash[k.to_sym] = v
            end
          when Enumerable
            return model.each_with_object({}) do |sub, hash|
              hash.merge!(parse_model(sub))
            end
          when NilClass
            return nil
          else
            raise "Incorrect model declaration, allowed String, Symbol, Hash and Enumerable. Given: #{model.class}"
          end
        end

      end
    end
  end
end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
eco-helpers-1.5.1 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.5.0 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.4.2 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.19 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.4.1 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.4.0 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.18 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.17 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.16 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.15 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.14 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.13 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.12 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.11 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.10 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.9 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.8 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.7 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.6 lib/eco/api/common/class_hierarchy.rb
eco-helpers-1.3.5 lib/eco/api/common/class_hierarchy.rb