Generic + Smart – link_to_s link_to_edit link_to_destroy

Building on my work in Separate Rights Management from Controllers i killed all linking-view-logic.

Example

before:
(movie.online? or movie.owner_id==current_user.id) ?
  link_to(movie,movie) : ''
(movie.owner_id==current_user.id) ?
  link_to('edit',movie) : ''

after:
link_to_s(movie)
link_to_edit(movie)

Code

#app/helpers/link_helper.rb
module LinkHelper
  def is_record?(something)
    something.kind_of?(ActiveRecord::Base)
  end

  def can_write?(obj)
    user = current_user || User.new
    user.can_write?(obj)
  end

  def can_read?(obj)
    user = current_user || User.new
    user.can_read?(obj)
  end

  #can we build a link ?
  #true if it is an id / path
  #false if it is an record and i cannot reda/write it
  def is_linkable?(object,rw)
    raise ":r or :w" unless [:r,:w].include? rw
    return false unless object
    return true unless is_record?(object)
    return rw == :r ? can_read?(object) : can_write?(object)
  end

  def link_to_s(object,options={})
    return "" unless is_linkable?(object,:r)
    link_to(object.to_s,object,options)
  end

  def link_to_edit(path_or_object,options={})
    return "" unless is_linkable?(path_or_object,:w)
    if is_record?(path_or_object)
      path_or_object = edit_polymorphic_path(path_or_object)
    end
    link_to("edit",path_or_object,options)
  end

  def link_to_destroy(path_or_object,options={})
    return "" unless is_linkable?(path_or_object,:w)
    link_to( 'X', path_or_object, options.merge(:class=>'destroy'))
  end
end

Please drop a comment if you can think of enhancements, if i can find more uses/methods i will build a new link-helper-plugin 🙂

Advertisements

3 thoughts on “Generic + Smart – link_to_s link_to_edit link_to_destroy

  1. Looks really nice, I’ll have to try something like this on an upcoming project 🙂

    BTW, can_read?(obj) and can_write?(obj) look awfully similar to your controller methods of the same name. I suppose you have something like the following on your controllers:

    def can_read?(obj=nil)
    user = current_user || User.new
    user.can_read?(obj || requested_object)
    end
    helper_method :can_read?

    (ditto for can_write?)

  2. Ctrl+c Ctrl+v
    now i have 🙂

    i like the obj=nil idea, so far i used 2 different methods on controller(without argument)/helper(with argument)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s