How to create a custom method for the rails console?

前端 未结 3 1935
情话喂你
情话喂你 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:05

    Put this function to ~/.irbrc

    def clear
      system 'clear'
    end
    

    Then it'll be available when you run irb.

    0 讨论(0)
  • 2021-01-06 05:14

    Just put it in the ~/.irbrc file. It gets loaded every time you run irb or rails console. The Rails console is just irb with your Rails application environment loaded.

    Find more infos about irb here: http://ruby-doc.com/docs/ProgrammingRuby/html/irb.html#S2

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题