This is how to convert a string to a class in Rails/Ruby:
p = "Post" Kernel.const_get(p) eval(p) p.constantize
But what if I am retrieving a method from an array/active record object like:
Post.description
but it could be
Post.anything
where anything is a string like anything = "description"
.
This is helpful since I want to refactor a very large class and reduce lines of code and repetition. How can I make it work?
Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.
We can convert a string to setin Python using the set() function. Parameters : Any iterable sequence like list, tuple or dictionary. Returns : An empty set if no element is passed. Non-repeating element iterable modified as passed as argument.
String Into Variable Name in Python Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.
Post.send(anything)
While eval can be a useful tool for this sort of thing, and those from other backgrounds may take to using it as often as one might a can opener, it's actually dangerous to use so casually. Eval implies that anything can happen if you're not careful.
A safer method is this:
on_class = "Post" on_class.constantize.send("method_name") on_class.constantize.send("method_name", arg1)
Object#send will call whatever method you want. You can send either a Symbol or a String and provided the method isn't private or protected, should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With