Module: Endeca::Readers::ClassMethods
- Defined in:
- lib/endeca/readers.rb
Instance Method Summary collapse
- #add_reader(name, &block) ⇒ Object
-
#boolean_reader(*attrs) ⇒ Object
Typecasts attributes as a Perly boolean (“0” == false, “1” == true“).
-
#decimal_reader(*attrs) ⇒ Object
Typecasts attributes as BigDecimal.
-
#float_reader(*attrs) ⇒ Object
Typecasts attributes as floats .
-
#integer_reader(*attrs) ⇒ Object
Typecasts attributes as integers.
-
#reader(*attrs, &block) ⇒ Object
Maps key/value pairs from the data structure used to initialize a Endeca object.
Instance Method Details
#add_reader(name, &block) ⇒ Object
6 7 8 9 10 11 |
# File 'lib/endeca/readers.rb', line 6 def add_reader(name, &block) = (class << self; self; end) .instance_eval do define_method(name) { |*attrs| reader(*attrs, &block) } end end |
#boolean_reader(*attrs) ⇒ Object
Typecasts attributes as a Perly boolean (“0” == false, “1” == true“)
Examples
boolean_reader :price
84 85 86 |
# File 'lib/endeca/readers.rb', line 84 def boolean_reader(*attrs) reader(*attrs) { |value| value == "1" ? true : false } end |
#decimal_reader(*attrs) ⇒ Object
Typecasts attributes as BigDecimal
Examples
decimal_reader :price
59 60 61 62 |
# File 'lib/endeca/readers.rb', line 59 def decimal_reader(*attrs) require 'bigdecimal' unless defined?(BigDecimal) reader(*attrs) { |value| BigDecimal(value.to_s) } end |
#float_reader(*attrs) ⇒ Object
Typecasts attributes as floats
Examples
float_reader :latitude, :longitude
68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/endeca/readers.rb', line 68 def float_reader(*attrs) reader(*attrs) do |value| if value if value.respond_to?(:to_f) value.to_f else Float(value) end end end end |
#integer_reader(*attrs) ⇒ Object
Typecasts attributes as integers.
Examples
integer_reader :id, :rating
51 52 53 |
# File 'lib/endeca/readers.rb', line 51 def integer_reader(*attrs) reader(*attrs) { |value| value.blank? ? 0 : Integer(value) } end |
#reader(*attrs, &block) ⇒ Object
Maps key/value pairs from the data structure used to initialize a Endeca object. Allows attribute renaming. Use a block to perform data injunction on the value as it is set.
Examples
# Specify basic attributes
reader :title
# Attribute renaming
reader :long_desc => :description
# Data injunction
reader(:title => :upcased_title) { |title| title.upcase }
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/endeca/readers.rb', line 27 def reader(*attrs,&block) hash = {} block ||= lambda {|x| x} hash.update(attrs.pop) if Hash === attrs.last attrs.each{ |attr| hash[attr] = attr } hash.each do |variable, method| reader_names << method if respond_to?(:reader_names) define_method(method) do begin block.call(attributes[variable.to_s]) rescue StandardError => e raise Endeca::ReaderError, e. end end end end |