Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/linki/getter_for

Adds getter methods for attributes that the object belongs to
https://github.com/linki/getter_for

Last synced: about 2 months ago
JSON representation

Adds getter methods for attributes that the object belongs to

Awesome Lists containing this project

README

        

h1. Getter For


gem install getter_for

h2. Setup

image you have a ticket model that belongs to a user. you can add convenience methods for any user attribute like that:


class Ticket < ActiveRecord::Base
belongs_to :user

getter_for :user => :name
end

@ticket = Ticket.new
@ticket.user_name # => @ticket.user.name if @ticket.user

That method returns nil if user is nil, so it can safely used in your views

You can pass multiple key/value pairs separated by comma and provide arrays for both model name and method name. let me show you:


class Project < ActiveRecord::Base
belongs_to :category
belongs_to :user
belongs_to :assignee, :class_name => 'User'

getter_for [:category, :user] => :name,
:assignee => [:email, :phone]
end

@project = Project.new
@project.category_name # => @project.category.name if @project.category
@project.user_name # => @project.user.name if @project.user
@project.assignee_email # => @project.assignee.email if @project.assignee
@project.assignee_phone # => @project.assignee.phone if @project.assignee

you can also make fancy stuff like:


class User < ActiveRecord::Base
belongs_to :department
getter_for :department => :name # => user.department_name
end

class Comment < ActiveRecord::Base
belongs_to :user
getter_for :user => :department_name # => comment.user_department_name
end

@comment = Comment.new
@comment.user_department_name # => @comment.user.department.name if @comment.user && @comment.user.department

Copyright (c) 2009 Martin Linkhorst, released under the MIT license.