Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

add explict support for converting active_record objects.

  • Loading branch information...
commit e8be999255a2188f5d1fd9afdcbf883385967704 1 parent 028bddc
ara.t.howard authored February 07, 2010
1  lib/hashish.rb
@@ -53,6 +53,7 @@ def libdir(*args, &block)
53 53
     load 'slug.rb'
54 54
     load 'parameter_parser.rb'
55 55
     load 'api.rb'
  56
+    load 'rails.rb' if defined?(Rails)
56 57
   end
57 58
 
58 59
   unless defined?(H)
59  lib/hashish/rails.rb
... ...
@@ -0,0 +1,59 @@
  1
+if defined?(Rails)
  2
+
  3
+  ActiveRecord
  4
+  ActiveRecord::Base
  5
+
  6
+  module ActiveRecord
  7
+    class Base
  8
+      class << self 
  9
+        def to_hashish(*args)
  10
+
  11
+          @to_hashish ||= (
  12
+            column_names + reflect_on_all_associations.map(&:name)
  13
+          ).map{|name| name.to_s}
  14
+
  15
+          unless args.empty?
  16
+            @to_hashish.clear
  17
+            args.flatten.compact.each do |arg|
  18
+              @to_hashish.push(arg.to_s)
  19
+            end
  20
+            @to_hashish.uniq!
  21
+            @to_hashish.map!{|name| name.to_s}
  22
+          end
  23
+
  24
+          @to_hashish
  25
+        end
  26
+
  27
+        alias_method 'to_h', 'to_hashish'
  28
+      end
  29
+
  30
+      def to_hashish(*args)
  31
+        hash = Hashish.data
  32
+        model = self.class
  33
+
  34
+        attrs = args.empty? ? model.to_hashish : args
  35
+
  36
+        attrs.each do |attr|
  37
+          value = self.send(attr)
  38
+
  39
+          if value.respond_to?(:to_hashish)
  40
+            hash[attr] = value.to_hashish
  41
+            next
  42
+          end
  43
+
  44
+          if value.is_a?(Array)
  45
+            hash[attr] = value.map{|val| val.respond_to?(:to_hashish) ? val.to_hashish : val}
  46
+            next
  47
+          end
  48
+
  49
+          hash[attr] = value
  50
+        end
  51
+
  52
+        hash
  53
+      end
  54
+
  55
+      alias_method 'to_h', 'to_hashish'
  56
+    end
  57
+  end
  58
+
  59
+end

0 notes on commit e8be999

Please sign in to comment.
Something went wrong with that request. Please try again.