Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting a local variable to a binding

I am trying to set a local variable to an existing binding

def foo_callback
  lambda { |name| p name }
end
b = foo_callback.binding

The binding doesn't have any local variables to begin with:

b.eval("local_variables") # => []

Let us set a primitive local variable to the binding:

b.eval("age=30")

Everything works as expected:

b.eval("local_variables") # => ["age"]
b.eval("age") # => 30

Now, let us try to set a non-primitive local variable to the binding:

country = Country.first
b.eval("lambda {|v| country = v}").call(country)

Note: The technique for setting the variable is borrowed from the facet gem. I tried the ruby 1.9 safe implementation with same results.

The binding does not reflect the local variable country.

b.eval("local_variables") # => ["age"]

How do I get around this issue? Essentially, I want to declare a new variable in a binding using the value of an existing, non primitive variable.

I am on Ruby 1.8.7.

like image 432
Harish Shetty Avatar asked Mar 12 '12 18:03

Harish Shetty


People also ask

Is SQL injection possible when using bind variables?

Strictly speaking is SQL injection indeed possible when using bind variables. The query below use BV and can be subject of SQL injection in case the parameter column_list is manipulated.

How to bind a variable to an integer in Java?

According to the datatype of the bind variable, you need to select the respective setter method. Here, in this case, the data type of the bind variable is integer therefore, we need to use setInt () method.

What are bind variables?

What are bind variables? How to execute a query with bind variables using JDBC? A bind variable is an SQL statement with a temporary variable as place holders which are later replaced with appropriate values. For example, if you have a table named employee in the database created as shown below:

What is property dependency injection?

Property Injection: When the Injector injects the dependency object (i.e. service) through the public property of the client class, then it is called Property Dependency Injection. This is also called the Setter Injection.


1 Answers

You're creating country outside of the binding, and then the country inside the lambda is only valid within that scope. Why not eval it if you need to inject that into the binding as well?

Update

Try declaring the variable outside of the scope of the lambda but inside the scope of the binding:

 b.eval("country = nil; lambda {|v| country = v}").call(country)
like image 126
tadman Avatar answered Sep 28 '22 03:09

tadman