Tuesday, 15 September 2015

ruby - rails 4 lib folder versus initializers folder -



ruby - rails 4 lib folder versus initializers folder -

i have few functions monkey patch string class in file named string_class.rb placed in config\initializers\string_class.rb. code looks this:

class string def capitalize_first_char self.sub(/^(.)/) { $1.capitalize } end def capitalize_each_sentence self.gsub(/([a-z])((?:[^.?!]|\.(?=[a-z]))*)/i) { $1.upcase + $2.rstrip } end end

after doing quite bit of research on fence if class should live in initializers or lib folder. turn fellow geeks answers on this, , bit of guidance.

there isn't place sort of thing live in rails application, because it's not sort of thing should doing through normal course of study of building rails app. patching core classes expressly advised against in pretty much every style-guide going.

config/initializers wrong place this. typically setting dependencies app, , people won't think there code mixing unusual methods core classes lib improve place, it's not auto-reloaded default gemfile? if worth patching string, might worth distilling gem , thoroughly documenting.

i sidestep problem , introduce helper methods. can create helper methods available across controllers defining them in app/controllers/application_controller.rb. can create methods available views helper_method function:

class applicationcontroller < actioncontroller::base helper_method :capitalize_first_char, :capitalize_each_sentence #... protected def capitalize_first_char(str) str.sub(/^(.)/) { $1.capitalize } end def capitalize_each_sentence(str) str.gsub(/([a-z])((?:[^.?!]|\.(?=[a-z]))*)/i) { $1.upcase + $2.rstrip } end end

ruby-on-rails ruby folders monkeypatching

No comments:

Post a Comment