Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string to a class method?

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?

like image 584
kgpdeveloper Avatar asked May 26 '10 13:05

kgpdeveloper


People also ask

How do you convert a string to a class object in Python?

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.

Can we convert string into set?

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.

How do you convert a string to a variable?

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.


2 Answers

Post.send(anything) 
like image 177
shingara Avatar answered Sep 28 '22 20:09

shingara


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.

like image 28
tadman Avatar answered Sep 28 '22 18:09

tadman