Reputation: 6259
I want to interpolate my Javascript Code with a Ruby Function. For example:
def find_house name
......
end
def map_houses
%{
function() {
var name = this.name;
var house_data = #{find_house(this.name)};
............
}
}
end
But, it doesn't work like this, i get an error for this line:
var house_data = #{find_house(this.name)};
It says this.name
is Undefinded
.
How can I pass a javascript argument to this function? Thanks
Upvotes: 0
Views: 684
Reputation: 15056
If I understand correctly, you want to interpolate the value of find_house
into javascript, which will be executed elsewhere. It looks pretty close, but you do need to make a couple of changes.
def map_houses
%Q{
function() {
var name = this.name;
var house_data = "#{find_house(this.name)}";
............
}
}
end
%Q
allows you to interpolate into a multi-line string, whereas %q
does not. It's kind of like the difference between ''
and ""
. The other change is that you will still want to wrap the interpolated value in ""
so that the resulting javascript is properly wrapped in a string, assuming that var house_data
is a string. If it's supposed to be a JSON object, then you'll want to remove the quotes and ensure that you're calling to_json
on whatever value is interpolated there.
You can probably just drop the quotes wrapping the interpolation and call to_json
on any value, and it will interpolate correctly. "some string".to_json #=> "\"some string\""
, which interpolates to "some string"
, for example.
Upvotes: 1