Search code examples
rubycalabash

What's the cleanest way to define a constant string that involves a variable in Ruby?


For some context, a lot of my code has the same lines of text throughout it (we are using Calabash to do iOS automation, if that gives you an idea).

For example: "all label marked:'#{name}'" is used 8 times in a particular class.

I would prefer to be able to have a constant that uses that text, but if I throw it at the top of the class, of course the variable "name" has not been set yet. Without defining a method that takes a parameter and returns a string, is there a way to do something essentially like this that can exist at the top of the class, but not be evaluated until it's used?:

class ClassName
  extend Calabash::Cucumber::Operations

  @NAME_CONSTANT = "all label marked:'#{name}'"

  def self.method_name(name)
    query("#{@NAME_CONSTANT} sibling label marked:'anotherLabel' isHidden:0")
  end
end

If you use the syntax I mentioned, you get this error: undefined local variable or method `name' for ClassName


Solution

  • You could use String#% to insert the string later.

    class ClassName
        @NAME_CONSTANT = "all label marked:'%{name}'"
    
        def self.method_name(insert_name)
            query("#{@NAME_CONSTANT} sibling label marked:'anotherLabel' isHidden:0" % {name: insert_name})
        end
    
        def self.query(string)
            puts string
        end 
    end 
    
    ClassName.method_name('test')
    #=> "all label marked:'test' sibling label marked:'anotherLabel' isHidden:0"