rubysinatradatamapperruby-datamapper

How to list possible Enum symbols in sinatra view?


Say I have a model like so:

class Animal
    include DataMapper::Resource
    property :id, Serial
    property :type, Enum[ :cat, :bat, :rabbit, :zebra]
end

Assuming there is a route pointing to an erb template for adding more animals & @animal = session[:animal] how would I create a list of animal types?

...
<form>
  <% @animal.type.each do |animal| %>
    <select>
      <option value="<%= @animal.type" %></option>
    </select>
  <% end %> 
</form>

(Obviously that bit of code doesn't do what I am looking for, but I hope it makes it a little more clear.)


Solution

  • There is flags option on the property that you can use to lookup the enum values. I don't know where this is documented - I found it here. So you could do something like this:

    <form>
      <select>
        <% Animal.type.options[:flags].each do |animal| %>
          <option value="<%= animal %>"><%= animal %></option>
        <% end %>
      </select>
    </form>
    

    I guess you could generalise this into a helper method.