ruby - Rails override flash -


in application, need show several flashes, of same type. in cases,

my_controller#some_action

flash[:alert] = [] ... flash[:alert] << error1 if something_bad_happened ... flash[:alert] << error2 if something_else_bad_happened 

and in view iterate on each flash type , check if flash normal flash or array of flashes.

flash.each |type, val|   if flash[:type].is_a?(array)    flash[:type].each |fl|      render_flash(fl)    end   else    render_flash(flash[:type])   end end 

this cool , works well, in code end mix of actions use standard flash , "array" flash, , find stupid.

is there way override flash setters that

flash[:alert] = error_x 

...would push error_x array of flash ?

edit:

the above code used handling "array of flashes" quick way found achieve goal, if you're telling me unclean , have better solution, i'm taking (or @ least i'll keep in mind when have similar stuff in future). put code explain bit context

edit 2:

i end mix of actions use standard flash , "array" flash

i mean example, in controllers may have

flash.error = error_message #or render 'something', alert: error_message # or flash[:error] = error_message 

now, refining lot of code, , somewhere else in helper, may want show additional error message, assuming flash array

class mycontroller < applicationcontroller     def action         if my_command_failed           flash[:alert] = "your command failed" # let's suppose it's original []= method of flash here            myhelper::sometools.fix_stuff          end         redirect_to after_error_path     end end  class myhelper::sometools     def fix_stuff       ...       flash[:alert] << "oh btw, there error here..."            # ... crash, i'd have "clever code", fix mistake me (so making array both error messages)     end end 

given eugene petrov pointed out in comment flash messages can primitive, can consider make value array if feel need have array in cases.

you can create wrapper around flash in applicationcontroller forces input converted , assigned array.

def multiflash(type, message)   flash[type] ||= []   flash[type] << message end 

and use in controllers.

in view, pretend flash array.

<% flash.each |type, val| %>   <% flash[:type].each |fl| %>      render_flash(fl)   <% end %> <% end %> 

as noticed, it's not idea have keys sometime stores arrays , other times strings.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -