Question

Imagine a resource: /users/14/notifications. It implements several HTTP verbs/methods: GET, GET/edit, POST, DELETE.

All 4 actions share a small part of logic: retrieve all notifications, create some hash for easy access, fetch some specific user access from somewhere else to do something special etc. Just a few loc (let's say 7).

How can I reuse those 7 loc to keep the logic DRY? I've heard about Rails' ANY verb, but I have no idea how to use it. Also no idea how to use its result (a few vars) in the 4 actual actions.

I would expect something like:

def any
  @notifications = Notification.find_by etc...
  // do something here to create
  @reverse_notifications_hash = ...
  // and something else
  @super_special_access = ...
end

def show
  // Only specific logic here
  // Render using @notifications
end

def edit
  // Only specific logic here
  // Render form using @notifications,
  // @reverse_notifications_hash and
  // @super_special_access
end

def update 
  // Only specific logic here
  // Fetch something else special to not override stuff or be extra efficient
  more_special = ...
  // Do update stuff with @notifications, @super_special_access and more_special
end

As you might have noticed, I'm not a pro Ruby/Railser. (The syntax might even be wrong.) I am very curious though.

How would it actually work in RoR?

Was it helpful?

Solution

Try using a before filter to execute the common code. In your example you could add this line to your controller before_filter :any.

EDIT:

Also changed the visibility of any to private or protected so that it can't be exposed as controller action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top