How to create a custom method for the rails console?

前端 未结 3 1961
情话喂你
情话喂你 2021-01-06 04:54

When I\'m using the Rails console in Ubuntu for a long session I define the clear method:

def clear; system \'clear\' end

So when m

3条回答
  •  长发绾君心
    2021-01-06 05:26

    In case you like to define your console helpers in the realm of your rails-project-directory, there's another interesting approach: You can extend the Rails::ConsoleMethods-module, which holds well-known and handy console-stuff like app, helper, controller etc... Here's one easy way to do this:

    Just add a module to your lib-directory that holds your custom console helpers and apply it to Rails::ConsoleMethods via mixin prepending - e.g.:

    # Extending Rails::ConsoleMethods with custom console helpers
    module CustomConsoleHelpers
    
      # ** APP SPECIFIC CONSOLE UTILITIES ** #
    
      # User by login or last
      def u(login=nil)
        login ? User.find_by_login!(login) : User.last
      end
    
      # Fav test user to massage in the console
      def honk
        User.find_by_login!("Honk")
      end
    
      # ...
    
      # ** GENERAL CONSOLE UTILITIES ** #
    
      # Helper to open the source location of a specific 
      # method definition in your editor, e.g.:
      #
      #   show_source_for(User.first, :full_name)
      #
      # 'inspired' (aka copy pasta) by 'https://pragmaticstudio.com/tutorials/view-source-ruby-methods' 
      def show_source_for(object, method)
        location = object.method(method).source_location
        `code --goto #{location[0]}:#{location[1]}` if location
        location
      end
    
      # ...
    end
    
    require 'rails/console/helpers'
    Rails::ConsoleMethods.send(:prepend, CustomConsoleHelpers)
    

    This works for me like a charm. Further alternatives to this approach (which I didn't test) would be to either put the above in an initializer (like here) - or to extend Rails::ConsoleMethods in config/application.rb instead - e.g. like this (found here and here):

    console do
      require 'custom_console_helpers'
      Rails::ConsoleMethods.send :include, CustomConsoleHelpers
    end
    

提交回复
热议问题