Sha256: 4ab983ba929ac8b1bf0e6dd6fca5f2a984f2e7f44eae9b1f26e369ccd0775667
Contents?: true
Size: 1.8 KB
Versions: 2
Compression:
Stored size: 1.8 KB
Contents
require 'active_model' require "active_support/concern" module Quandl module Support module Attributes extend ActiveSupport::Concern included do extend ActiveModel::Callbacks define_model_callbacks :initialize, only: [:after] end module ClassMethods def inherited(subclass) subclass.define_attributes(*attributes) end def define_attributes(*attribute_names) attribute_names.each do |key| define_attribute(key) end end def attributes @attributes ||= [] end protected def define_attribute(key) key = key.to_s attributes << key unless attributes.include?(key) define_method( key ){ read_attribute(key) } define_method( "#{key}=" ){ |value| write_attribute(key, value) } define_method( "#{key}?" ){ !read_attribute(key).nil? } end end def initialize(*args) run_callbacks(:initialize) do attrs = args.extract_options! # apply _attributes directly to @attributes @attributes = attrs[:_attributes].is_a?(Hash) ? attrs.delete(:_attributes) : {} # apply attrs through write_attribute self.attributes = attrs if attrs.is_a?(Hash) # onwards super(*args) if defined?(super) end end def attributes=(new_attrs) new_attrs.stringify_keys.each do |attr_key, attr_value| # skip those attributes that are not defined next unless self.class.attributes.include?(attr_key) && self.respond_to?("#{attr_key}=") # pass to the attribute writer self.send( "#{attr_key}=", attr_value ) end end def attributes @attributes ||= {} end protected def read_attribute(key) @attributes[key.to_s] end def write_attribute(key, value) @attributes ||= {} @attributes[key.to_s] = value end end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
quandl_data-1.5.1 | lib/quandl/support/attributes.rb |
quandl_data-1.5.0 | lib/quandl/support/attributes.rb |