Module: ActsAsIntegerInfinitable::ClassMethods
- Defined in:
- lib/acts_as_integer_infinitable.rb
Instance Method Summary collapse
-
#acts_as_integer_infinitable(fields, options = {}) ⇒ Object
Allows the fields to store an Infinity value.
Instance Method Details
#acts_as_integer_infinitable(fields, options = {}) ⇒ Object
Allows the fields to store an Infinity value.
Overrides the setter and getter of those fields in order to capture and return Infinity when appropiate.
Then you can use it as any other value and get the desired result, like decrementing, incrementing, comparing with <, >, ==, etc.
Example:
class LibrarySubscription < ActiveRecord::Base
acts_as_integer_infinitable [:available_books]
def rent_book
# Do other things...
self.available_books -= 1
save
end
end
> simple_subscription = LibrarySubscription.new(available_books: 5)
> simple_subscription.available_books
=> 5
> simple_subscription.rent_book
> simple_subscription.available_books
=> 4
> complete_subscription = LibrarySubscription.new(available_books: Float::INFINITY)
> long_subscription.available_books
=> Infinity
> long_subscription.rent_book
> long_subscription.available_books
=> Infinity
Parameters
-
fields
- An Array with the fields that will be infinitable. They have to be integers in the database.
Options
-
:infinity_value
- The value that will be converted to Infinity. Default: -1. Another popular value is ‘nil`.
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/acts_as_integer_infinitable.rb', line 48 def acts_as_integer_infinitable(fields, = {}) [:infinity_value] = -1 unless .key? :infinity_value fields.each do |field| define_method("#{field}=") do |value| int_value = value == Float::INFINITY ? [:infinity_value] : value write_attribute(field, int_value) end define_method("#{field}") do value = read_attribute(field) value == [:infinity_value] ? Float::INFINITY : value end end end |