Sha256: 84671cb02842ddc3b6e90b0b77225ce2de519fad7e5045f73e87c8c8afbb1de2

Contents?: true

Size: 1.46 KB

Versions: 24

Compression:

Stored size: 1.46 KB

Contents

require 'yao/resources/restfully_accessible'
require 'time'

module Yao::Resources
  class Base
    def self.friendly_attributes(*names)
      names.map(&:to_s).each do |name|
        define_method(name) do
          if !@data.key?(name) && id
            @data = self.class.get(id)
          end
          self[name]
        end
      end
    end

    def self.map_attribute_to_attribute(k_and_v)
      as_json, as_method = *k_and_v.to_a.first.map(&:to_s)
      define_method(as_method) do
        self[as_json]
      end
    end

    def self.map_attribute_to_resource(k_and_v)
      _name, klass = *k_and_v.to_a.first
      name = _name.to_s
      define_method(name) do
        self[[name, klass].join("__")] ||= klass.new(self[name])
      end
    end

    def self.map_attribute_to_resources(k_and_v)
      _name, klass = *k_and_v.to_a.first
      name = _name.to_s
      define_method(name) do
        self[[name, klass].join("__")] ||= self[name].map {|d|
          klass.new(d)
        }
      end
    end

    def initialize(data_via_json)
      @data = data_via_json
    end

    def [](name)
      @data[name]
    end

    def []=(name, value)
      @data[name] = value
    end

    def id
      self["id"]
    end

    def created
      if date = self["created"] || self["created_at"]
        Time.parse(date)
      end
    end

    def updated
      if date = self["updated"] || self["updated_at"]
        Time.parse(date)
      end
    end

    extend RestfullyAccessible
  end
end

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
yao-0.13.1 lib/yao/resources/base.rb
yao-0.13.0 lib/yao/resources/base.rb
yao-0.12.0 lib/yao/resources/base.rb
yao-0.11.3 lib/yao/resources/base.rb
yao-0.11.2 lib/yao/resources/base.rb
yao-0.11.1 lib/yao/resources/base.rb
yao-0.11.0 lib/yao/resources/base.rb
yao-0.10.1 lib/yao/resources/base.rb
yao-0.10.0 lib/yao/resources/base.rb
yao-0.9.1 lib/yao/resources/base.rb
yao-0.9.0 lib/yao/resources/base.rb
yao-0.8.0 lib/yao/resources/base.rb
yao-0.7.0 lib/yao/resources/base.rb
yao-0.6.3 lib/yao/resources/base.rb
yao-0.6.2 lib/yao/resources/base.rb
yao-0.6.1 lib/yao/resources/base.rb
yao-0.6.0 lib/yao/resources/base.rb
yao-0.5.0 lib/yao/resources/base.rb
yao-0.4.3 lib/yao/resources/base.rb
yao-0.4.2 lib/yao/resources/base.rb