Module: Ronin::Model::InstanceMethods

Defined in:
lib/ronin/model/model.rb

Overview

Instance methods that are added when Ronin::Model is included into a class.

Instance Method Summary collapse

Instance Method Details

#humanize_attributes(options = {}) {|name, value| ... } ⇒ Hash{String => String}

Formats the attributes of the model into human readable names and values.

Parameters:

  • options (Hash) (defaults to: {})

    Additional options.

Options Hash (options):

  • :exclude (Array<Symbol>) — default: []

    A list of attribute names to exclude.

Yields:

  • (name, value)

    If a block is given, it will be passed the name and humanized value of each attribute.

Yield Parameters:

  • name (String)

    The humanized name of the attribute.

  • value (String)

    The human readable value of the attribute.

Returns:

  • (Hash{String => String})

    A hash of the humanly readable names and values of the attributes.


121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/ronin/model/model.rb', line 121

def humanize_attributes(options={})
  exclude = [:id, :type]

  if options[:exclude]
    exclude += options[:exclude]
  end

  formatter = lambda { |value|
    if value.kind_of?(Array)
      value.map(&formatter).join(', ')
    elsif value.kind_of?(Symbol)
      Support::Inflector.humanize(value)
    else
      value.to_s
    end
  }

  formatted = {}

  self.attributes.each do |name,value|
    next if (value.nil? || (value.respond_to?(:empty?) && value.empty?))

    unless (exclude.include?(name) || value.nil?)
      name = name.to_s

      unless name[-3..-1] == '_id'
        name = Support::Inflector.humanize(name)
        value = formatter.call(value)

        if block_given?
          yield name, value
        end

        formatted[name] = value
      end
    end
  end

  return formatted
end