Created
June 15, 2009 21:27
-
-
Save brianmario/130356 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Patch to ActiveResource (based on the 2.3.2 codebase) for including the class name in the JSON generated. | |
| # This is so the receiving end (Rails) can more easily manage the params hash. | |
| # | |
| # The current implementation sends the attributes as top-level JSON keys, which ends up on the other end as: | |
| # params[:some_attribute] | |
| # params[:some_other_attribute] | |
| # params[:something_else] # => not related to the posted JSON | |
| # | |
| # This makes it hard to do things like: | |
| # obj = SomeModel.new(params[:some_model]) | |
| # | |
| # The patch changes this to include the ActiveResource class name in the JSON like ActiveRecord using | |
| # an include_root_in_json option. | |
| # | |
| # With this patch, the receiving end (Rails) can now have a scoped params hash like: | |
| # params[:some_model][:some_attribute] | |
| # | |
| # And as a result be able to do things like: | |
| # obj = SomeModel.new(params[:some_model]) | |
| # | |
| # As you normally do from a form post; Minimizing unnecessary code paths and a much DRYer code base overall. | |
| # Current implementation (ActiveResource::Base) | |
| def encode(options={}) | |
| case self.class.format | |
| when ActiveResource::Formats[:xml] | |
| self.class.format.encode(attributes, {:root => self.class.element_name}.merge(options)) | |
| else | |
| self.class.format.encode(attributes, options) | |
| end | |
| end | |
| # Patched (ActiveResource::Base) | |
| cattr_accessor :include_root_in_json, :instance_writer => false | |
| def encode(options={}) | |
| case self.class.format | |
| when ActiveResource::Formats[:xml] | |
| self.class.format.encode(attributes, {:root => self.class.element_name}.merge(options)) | |
| else | |
| if ActiveResource::Formats[:json] && include_root_in_json | |
| self.class.format.encode({self.json_class_name => attributes}, options) | |
| else | |
| self.class.format.encode(attributes, options) | |
| end | |
| end | |
| end | |
| def json_class_name | |
| @json_class_name ||= self.class.name.demodulize.underscore | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment