Restflection

Restflection is a Ruby on Rails plugin designed for use in applications which follow RESTful conventions. It allows you to extract information about resources without necessarily knowing what they are called.

For example, instead of writing article_path, you could write restflect(:member).path. Why would you do this? You may have shared code, for instance layouts or library files, which need to make use of a resource, but because they operate on any number of different resources, they cannot refer to them by name. The plugin could also be of use to other plugins.

Installation instructions

Get it from GitHub.

Conventions

As mentioned above, Restflection assumes you follow “RESTful conventions”. What does this mean exactly? Well, if we are talking about an article resource:

How Restflection exposes itself

Once installed, you can use Restflection from the controller or the view via the restflect method:

restflect(on)

Returns an instance of Restflection::ResourceReflection

Two convenience methods are also provided by the view:

What ResourceReflection provides

Pretend we are reflecting on an speckled_hen resource…

And now for my last trick, the one that you’ve all been waiting for…

You can call path and it will call speckled_hen_path, you can call edit_path and it will call edit_speckled_hen_path, you can call formatted_edit_url and it will called formatted_edit_speckled_hen_url, you can call hash_for_formatted_my_god_this_is_long_path and it will call hash_for_formatted_my_god_this_is_long_speckled_hen_path...

Etcetera.

One more thing: Restflection looks up to see whether the action you are calling a url helper for is a member action. If it is, Restflection will automatically pass the member to the url helper. In other words, path becomes speckled_hen_path(@speckled_hen). However, if you specify any arguments then you’re on your own, buddy.

Rolling your own

If you’re using Restflection outside of a view or controller, you might want to create your own ResourceReflection like so: Restflection::ResourceReflection.new(controller, name). You should probably read the Restflection source a bit for more detail.

Other notes of noteworthiness