Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: more efficient way to convert table_name into object Model?

So.. I'm trying to do something like this:

"active_record_object" => ActiveRecordObject

with the following code:

ar_object = (object.singularize.split("_").each{|o| o.capitalize!}).join.constantize #convert to ActiveRecord object

is there a more efficient way to do this? chaining 7 string manipulation methods together seems a lil crazy for ruby.

like image 580
NullVoxPopuli Avatar asked Jul 24 '26 15:07

NullVoxPopuli


1 Answers

There's a method called classify for that:

"active_record_object".classify
 # => "ActiveRecordObject"

Edit: as pointed out in the comments, "active_record_object".classify.constantize gets you all the way.

like image 117
Michael Kohl Avatar answered Jul 27 '26 10:07

Michael Kohl