module Binky::Helper
Public Instance Methods
accessor_builder(k, v)
click to toggle source
Builds an instance variable as well as its class method accessors from a key value pair.
# File lib/binky/builder.rb, line 24 def accessor_builder(k, v) self.instance_variable_set("@#{k}", v) self.class.send(:define_method, "#{k}", proc {self.instance_variable_get("@#{k}")}) self.class.send(:define_method, "#{k}=", proc {|v| self.instance_variable_set("@#{k}", v)}) end
attribute_from_inner_key(elem, attr, in_key = nil)
click to toggle source
# File lib/binky/builder.rb, line 59 def attribute_from_inner_key(elem, attr, in_key = nil) {attr.to_sym => nested_hash_value(elem, in_key&.present? ? in_key : attr.to_s)} end
build_by_keys(json = {}, keys = nil) { |self| ... }
click to toggle source
Parses a given json structure looking for specific keys inside the structure. Keys are given through a block. The result of it it's stored on a instance variable called to_hash and accessible through accessors with same name.
# File lib/binky/builder.rb, line 9 def build_by_keys(json = {}, keys = nil) k = keys || json&.keys raise ArgumentError "keys argument is not an array" unless k&.respond_to?(:each) accessor_builder('to_h',{}) unless self.class.method_defined?(:as_json) json.transform_keys!(&:to_s) k&.reject!{|ky| ky.end_with?('=')} k&.each do |key| self.send("#{key}=",nested_hash_value(json, key.to_s)) @to_h&.merge!({key.to_sym => nested_hash_value(json,key.to_s)}) end yield self if block_given? self end
method_missing(name,*args)
click to toggle source
# File lib/binky/builder.rb, line 55 def method_missing(name,*args) accessor_builder(name.to_s.gsub(/=$/,''), args[0]) if name.to_s =~ /=$/ end
nested_hash_value(obj, key)
click to toggle source
Goes through a complex Hash nest and gets the value of a passed key.
First wil check whether the object has the key? method, which will mean it's a Hash and also if the Hash the method parameter key if obj.respond_to?(:key?) && obj.key?(key) If it's not a Hash will check if it's a Array instead, checking out whether it responds to a Array.each method or not. elsif obj.respond_to?(:each) For every Array found it make a recursive call to itself passing the last element of the array and the Key it's looking for. r = nested_hash_value(a.last, key)
# File lib/binky/builder.rb, line 42 def nested_hash_value(obj, key) if obj.respond_to?(:key?) && obj.key?(key) obj[key] elsif obj.respond_to?(:each) r = nil obj.find do |*a| r = nested_hash_value(a.last, key) end r end end