module ZohoHub::WithAttributes

Allows adding attributes to a class, as attr_accessors that can then be listed from the class or an instance of that class.

Example

class User
  include ZohoHub::WithAttributes

  attributes :first_name, :last_name, :email
end

User.attributes # => [:first_name, :last_name, :email]
User.new.attributes # => [:first_name, :last_name, :email]

user = User.new
user.first_name = 'Ricardo'
user.last_name = 'Otero'
user.first_name # => "Ricardo"

Public Class Methods

included(base) click to toggle source
# File lib/zoho_hub/with_attributes.rb, line 23
def self.included(base)
  base.extend ClassMethods
end

Public Instance Methods

assign_attributes(new_attributes) click to toggle source

This method and the correponding private methods are inspired from Rails ActiveModel github.com/rails/rails/blob/master/activemodel/lib/active_model/attribute_assignment.rb

# File lib/zoho_hub/with_attributes.rb, line 66
def assign_attributes(new_attributes)
  unless new_attributes.is_a?(Hash)
    raise ArgumentError, 'When assigning attributes, you must pass a hash as an argument'
  end

  return if new_attributes.empty?

  attributes = new_attributes.transform_keys(&:to_s)
  attributes.each do |k, v|
    assign_attribute(k, v)
  end
end
attributes() click to toggle source

Returns the list of attributes defined for the instance class.

# File lib/zoho_hub/with_attributes.rb, line 60
def attributes
  self.class.attributes
end

Private Instance Methods

assign_attribute(key, value) click to toggle source
# File lib/zoho_hub/with_attributes.rb, line 93
def assign_attribute(key, value)
  setter = :"#{key}="

  return public_send(setter, value) if respond_to?(setter)

  raise ArgumentError, "Unknown attribute #{key}"
end
attr_to_zoho_key(attr_name) click to toggle source
# File lib/zoho_hub/with_attributes.rb, line 81
def attr_to_zoho_key(attr_name)
  self.class.attr_to_zoho_key(attr_name)
end
zoho_key_to_attr(zoho_key) click to toggle source
# File lib/zoho_hub/with_attributes.rb, line 85
def zoho_key_to_attr(zoho_key)
  translations = self.class.zoho_key_translation

  return translations[zoho_key.to_sym] if translations.key?(zoho_key.to_sym)

  zoho_key.to_sym
end