olivernn / poirot

mustaches in your rails
http://olivernn.github.com/poirot
108 stars 21 forks source link

View class can't handle nested attributes #19

Closed Darcbar closed 12 years ago

Darcbar commented 12 years ago

How can I add a view class method for something like {{ user.username }}?

olivernn commented 12 years ago

From what I understand you can't access nested attributes in mustache using dot syntax. There are a couple of ways you can get around this though.

If the user object has been serialised then you should be able to access it like so:

{{#user}}
  {{username}}
{{/user}}

You could also define a method on you view object that returns the username, perhaps something like this:

def username
  @user.username
end

And then in your template you could do this:

{{username}}

If there are a lot of attributes within user that you want to access you could delegate these methods to the user, with ruby you could do something like this in your view class:

class MyView
  extend Forwardable

  def_delegator :@user, :username, :username
end

I think in rails they make delegation a little nicer so you could do this:

class MyView
  delegate :username, to: :user
end

Take a look at the following links if that isn't clear Rails delegate and Ruby's forwardable

Hope that helps!

Darcbar commented 12 years ago

Thats great, Thanks olivernn.