Permalink
Browse files

add explict support for converting active_record objects.

  • Loading branch information...
1 parent 028bddc commit e8be999255a2188f5d1fd9afdcbf883385967704 @ahoward ahoward committed Feb 8, 2010
Showing with 60 additions and 0 deletions.
  1. +1 −0 lib/hashish.rb
  2. +59 −0 lib/hashish/rails.rb
View
1 lib/hashish.rb
@@ -53,6 +53,7 @@ def libdir(*args, &block)
load 'slug.rb'
load 'parameter_parser.rb'
load 'api.rb'
+ load 'rails.rb' if defined?(Rails)
end
unless defined?(H)
View
59 lib/hashish/rails.rb
@@ -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.