JP Silvashy
JP Silvashy

Reputation: 48535

Ruby, MongoDB, don't complain about undefined methods?

So I'm using MongoDB in an app and the fields for my documents have grown but In my views I don't want to have to have like an if block for each attribute, how can I have rails just display the value of the attribute if it is exists otherwise just quietly do nothing?


Example:

Since Mongo is schema-less these values wouldn't be defined in earlier instances of my models.

<%= @company.address %>
<%= @company.longitude %>
<%= @company.latitude %>

How do I handle this?

Upvotes: 1

Views: 153

Answers (2)

Jonas Elfstr&#246;m
Jonas Elfstr&#246;m

Reputation: 31438

Mongoid supports field default values.

class Company
  include Mongoid::Document
  field :address, type: String, default: ""
end

Upvotes: 1

tadman
tadman

Reputation: 211690

If you want it to just cope, you can always implement your own method_missing on that class which just eats calls and returns nil:

class Company
  def method_missing(*args)
    nil
  end
end

This could sweep a number of problems under the carpet, so you probably want to be careful when doing this sort of thing.

You could also make an extension that lets you do this:

= @company.try_method(:address)

This will return nil if there is no address method if you add this in an initializer:

class Object
  def try_method(method, *args)
    respond_to?(method) ? send(method, *args) : nil
  end
end

The try method that's part of Rails will only work if a method may return nil, but not if the method is not defined.

Upvotes: 1

Related Questions