Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a string as method parameter to be interpolated later

Is it possible to pass a string to a method in ruby and have that method interpolate that string?

I have something like this in mind:

do_a_search("location = #{location}")
...
def do_a_search(search_string)
  location = .... #get this from another source
  Model.where(search_string)
end

The context is RoR but this is a general ruby question I think. I realise the example above looks a bit convoluted but I'm trying to refactor a bunch of very repetitive methods.

The issue is that if I put the string to be interpolated in double quotes, location doesn't exist when the method is called, if I put it in single quotes, it will never be interpolated...

What I really want to do is put it in single quotes and interpolate it later. I don't think this is possible, or am I missing something?

edit: to be clear (as I think I have oversimplified what I'm trying to do above), one of the issues here is that I might want to call this method in multiple contexts; I might actually want to call

do_a_search("country = #{country}")

or even

do_a_search("country = #{country} AND location = #{location})

(country also existing as a local var within my method). I therefore want to pass everything necessary for the substitution in my method call

I think the String.interpolate method from the facets gem would solve my problem but it doesn't work in rails 4

like image 928
sparky Avatar asked Dec 14 '22 23:12

sparky


1 Answers

For that purpose, % is used. First, create a string:

s = "location = %{location}"

Later, you can apply % to it:

s % {location: "foo"} # => "location = foo"

If you do not have to name the parameter(s), then it is simpler:

s = "location = %s"
s % "foo" # => "location = foo"
like image 175
sawa Avatar answered Feb 12 '23 10:02

sawa