Skip to content

Commit

Permalink
add explict support for converting active_record objects.
Browse files Browse the repository at this point in the history
  • Loading branch information
ahoward committed Feb 8, 2010
1 parent 028bddc commit e8be999
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/hashish.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def libdir(*args, &block)
load 'slug.rb' load 'slug.rb'
load 'parameter_parser.rb' load 'parameter_parser.rb'
load 'api.rb' load 'api.rb'
load 'rails.rb' if defined?(Rails)
end end


unless defined?(H) unless defined?(H)
Expand Down
59 changes: 59 additions & 0 deletions lib/hashish/rails.rb
Original file line number Original file line Diff line number Diff line change
@@ -0,0 +1,59 @@
if defined?(Rails)

ActiveRecord
ActiveRecord::Base

module ActiveRecord
class Base
class << self
def to_hashish(*args)

@to_hashish ||= (
column_names + reflect_on_all_associations.map(&:name)
).map{|name| name.to_s}

unless args.empty?
@to_hashish.clear
args.flatten.compact.each do |arg|
@to_hashish.push(arg.to_s)
end
@to_hashish.uniq!
@to_hashish.map!{|name| name.to_s}
end

@to_hashish
end

alias_method 'to_h', 'to_hashish'
end

def to_hashish(*args)
hash = Hashish.data
model = self.class

attrs = args.empty? ? model.to_hashish : args

attrs.each do |attr|
value = self.send(attr)

if value.respond_to?(:to_hashish)
hash[attr] = value.to_hashish
next
end

if value.is_a?(Array)
hash[attr] = value.map{|val| val.respond_to?(:to_hashish) ? val.to_hashish : val}
next
end

hash[attr] = value
end

hash
end

alias_method 'to_h', 'to_hashish'
end
end

end

0 comments on commit e8be999

Please sign in to comment.