Skip to content

Instantly share code, notes, and snippets.

@boriscy
Created January 29, 2014 16:16
Show Gist options
  • Save boriscy/8691367 to your computer and use it in GitHub Desktop.
Save boriscy/8691367 to your computer and use it in GitHub Desktop.
module Models::HstoreMap
def convert_hstore_to(to_type, *methods)
methods.each do |meth|
alias_method :"old_#{meth}", meth
define_method meth do
send(:"old_#{meth}").try(to_type)
end
end
end
def convert_hstore_to_decimal(*methods)
convert_hstore_to(:to_d, *methods)
end
def convert_hstore_to_time(*methods)
convert_hstore_to(:to_time, *methods)
end
def convert_hstore_to_timezone(*methods)
methods.each do |meth|
alias_method :"old_#{meth}", meth
class_eval <<-CODE, __FILE__, __LINE__ + 1
def #{meth}
return old_#{meth} if old_#{meth}.is_a?(Time)
Time.zone.parse(old_#{meth})
rescue
nil
end
CODE
end
end
def convert_hstore_to_date(*methods)
convert_hstore_to(:to_date, *methods)
end
def convert_hstore_to_integer(*methods)
convert_hstore_to(:to_i, *methods)
end
def convert_hstore_to_boolean(*methods)
methods.each do |meth|
alias_method :"old_#{meth}", meth
define_method :"#{meth}" do
if %w{true false}.include? send(:"old_#{meth}")
send(:"old_#{meth}") == "true" ? true : false
else
send(:"old_#{meth}")
end
end
define_method :"#{meth}?" do
!!send(meth)
end
end
end
end
class Expense < ActiveRecord::Base
# Store
EXTRA_COLUMNS = %i(bill_number gross_total original_total balance_inventory nuller_datetime null_reason approver_datetime delivered discounted devolution no_inventory).freeze
store_accessor( *([:extras] + EXTRA_COLUMNS))
# Extra methods defined for Hstore
extend Models::HstoreMap
convert_hstore_to_boolean :devolution, :delivered, :discounted, :no_inventory
convert_hstore_to_decimal :gross_total, :original_total, :balance_inventory
convert_hstore_to_timezone :nuller_datetime, :approver_datetime
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment