Sha256: 5ae6c111434114290d205bafd3f7e056e6dfad8f7984fda572d028274c55c5fe

Contents?: true

Size: 1.54 KB

Versions: 162

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 model [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

162 entries across 162 versions & 1 rubygems

Version Path
eco-helpers-2.1.2 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.1.1 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.68 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.67 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.66 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.65 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.64 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.63 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.62 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.61 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.60 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.59 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.58 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.57 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.56 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.55 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.54 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.53 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.52 lib/eco/api/common/class_hierarchy.rb
eco-helpers-2.0.51 lib/eco/api/common/class_hierarchy.rb