Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In Ruby terms, <code>"#{x}"</code> is simply equivalent to <code>x.to_s</code> which for String values is exactly the same as the string itself. In other languages, like PHP, you can de-reference a string and treat it as a class, but that's not the case here. What you probably mean is this:</p> <pre><code>fruit_class = fruit_type.titleize.singularize.constantize fruit_class.create(...) </code></pre> <p>The <code>constantize</code> method converts from a string to the equivalent class, but it is case sensitive.</p> <p>Keep in mind that you're exposing yourself to the possibility someone might create something with <code>fruit_type</code> set to <code>"users"</code> and then go ahead and make an administrator account. What's perhaps more responsible is to do an additional check that what you're making is actually of the right class.</p> <pre><code>fruit_class = fruit_type.titleize.singularize.constantize if (fruit_class.superclass == Fruit) fruit_class.create(...) else render(:text =&gt; "What you're doing is fruitless.") end </code></pre> <p>One thing to watch out for when loading classes this way is that <code>constantize</code> will not auto-load classes like having them spelled out in your application does. In development mode you may be unable to create subclasses that have not been explicitly referenced. You can avoid this by using a mapping table which solves the potential security problem and pre-loading all at once:</p> <pre><code>fruit_class = Fruit::SUBCLASS_FOR[fruit_type] </code></pre> <p>You can define this constant like this:</p> <pre><code>class Fruit &lt; ActiveRecord::Base SUBCLASS_FOR = { 'apples' =&gt; Apple, 'bananas' =&gt; Banana, # ... 'zuchini' =&gt; Zuchini } end </code></pre> <p>Using the literal class constant in your model will have the effect of loading them immediately.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload