Sha256: 57b22b32dd3de38caafcc61edd18d0e71bb4f2a35b38438f4a896a3672a114a2

Contents?: true

Size: 1.75 KB

Versions: 20

Compression:

Stored size: 1.75 KB

Contents

module BacklogKit
  class Resource
    def initialize(raw_data = {})
      @attributes = {}

      raw_data.each do |key, value|
        @attributes[key.to_sym] = process_value(value)
      end

      eigenclass = class << self; self; end
      eigenclass.send(:define_accessors, raw_data.keys)
    end

    class << self
      def define_accessors(attributes)
        attributes.each do |attribute|
          define_reader(attribute)
          define_writer(attribute)
          define_boolean_method(attribute)
        end
      end

      def define_reader(attribute)
        class_eval do
          define_method(attribute) do
            @attributes[attribute.to_sym]
          end

          alias_method(attribute.underscore, attribute)
        end
      end

      def define_writer(attribute)
        method_name = "#{attribute}="
        alias_method_name = "#{attribute.underscore}="

        class_eval do
          define_method(method_name) do |value|
            @attributes[attribute.to_sym] = value
          end

          alias_method(alias_method_name, method_name)
        end
      end

      def define_boolean_method(attribute)
        method_name = "#{attribute}?"
        alias_method_name = "#{attribute.underscore}?"

        class_eval do
          define_method(method_name) do
            !!@attributes[attribute.to_sym]
          end

          alias_method(alias_method_name, method_name)
        end
      end
    end

    private_class_method(
      :define_accessors,
      :define_reader,
      :define_writer,
      :define_boolean_method
    )

    private

    def process_value(value)
      case value
      when Hash  then self.class.new(value)
      when Array then value.map { |v| process_value(v) }
      else value
      end
    end
  end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
backlog_kit-0.19.0 lib/backlog_kit/resource.rb
backlog_kit-0.18.0 lib/backlog_kit/resource.rb
backlog_kit-0.17.0 lib/backlog_kit/resource.rb
backlog_kit-0.16.0 lib/backlog_kit/resource.rb
backlog_kit-0.15.0 lib/backlog_kit/resource.rb
backlog_kit-0.14.0 lib/backlog_kit/resource.rb
backlog_kit-0.13.0 lib/backlog_kit/resource.rb
backlog_kit-0.12.1 lib/backlog_kit/resource.rb
backlog_kit-0.12.0 lib/backlog_kit/resource.rb
backlog_kit-0.11.0 lib/backlog_kit/resource.rb
backlog_kit-0.10.0 lib/backlog_kit/resource.rb
backlog_kit-0.9.0 lib/backlog_kit/resource.rb
backlog_kit-0.8.0 lib/backlog_kit/resource.rb
backlog_kit-0.7.0 lib/backlog_kit/resource.rb
backlog_kit-0.6.0 lib/backlog_kit/resource.rb
backlog_kit-0.5.0 lib/backlog_kit/resource.rb
backlog_kit-0.4.0 lib/backlog_kit/resource.rb
backlog_kit-0.3.0 lib/backlog_kit/resource.rb
backlog_kit-0.2.0 lib/backlog_kit/resource.rb
backlog_kit-0.1.0 lib/backlog_kit/resource.rb