Class: Hash
Instance Method Summary collapse
-
#to_js(options = {}) ⇒ Object
Returns a Javascript string representing the hash.
Instance Method Details
#to_js(options = {}) ⇒ Object
Returns a Javascript string representing the hash.
Just like to_json, without any options
, the returned javascript equivalent the obejct For example:
{ :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_js
# => {"name": "Konata Izumi", 1: 2, "age": 16}
The keys in the javascript string are unordered due to the nature of hashes.
Also like to_jason, the :only
and :except
options can be used to limit the attributes included, and will accept 1 or more hash keys to include/exclude.
{ :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_js(:only => [:name, 'age'])
# => {"name": "Konata Izumi", "age": 16}
{ :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_js(:except => 1)
# => {"name": "Konata Izumi", "age": 16}
The options
also filter down to any hash values. This is particularly useful for converting hashes containing ActiveRecord objects or any object that responds to options in their to_js
method. For example:
users = User.find(:all)
{ :users => users, :count => users.size }.to_js(:include => :posts)
would pass the :include => :posts
option to users
, allowing the posts association in the User model to be converted to javascript as well.
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/to-javascript/encoders/hash.rb', line 31 def to_js( = {}) hash_keys = self.keys if [:except] hash_keys = hash_keys - Array([:except]) elsif [:only] hash_keys = hash_keys & Array([:only]) end returning result = ActiveSupport::JS::Code.new('{') do result << hash_keys.map do |key| "#{ActiveSupport::JS.encode(key)}: #{ActiveSupport::JS.encode(self[key], )}" end * ', ' result << '}' end end |