简体   繁体   English

从命令提示符运行Rails模块

[英]Running Rails module from Command Prompt

I have a module like this in my Rails application. 我的Rails应用程序中有一个像这样的模块。 I have a folder extras inside my app folder. 我的应用程序文件夹中有一个文件夹Extras。 Inside that i have a module. 在里面,我有一个模块。

module ExcelUpload
 class Eupload
   def do_something
   end 
 end

 def self.excel_upload
   upload_service = Eupload.new
   upload_service.do_something 
 end  
end

How to execute this above module from command prompt. 如何从命令提示符处执行以上模块。 I want to execute like rake tasks. 我想像耙任务一样执行。 Eg - bundle exec rake db:migrate 例如-捆绑exec rake db:migrate

Is there any command for this? 有什么命令吗?

module name should be the camel casing name of the folder in which you are keeping the .rb file. 模块名称应为要保存.rb文件的文件夹的驼峰式外壳名称。 Here it should be module Extras instead of module ExcelUpload 这里应该是module Extras而不是module ExcelUpload

suggest you to put that module in your \\lib folder of your application's directory structure. 建议您将该模块放入应用程序目录结构的\\lib文件夹中。 From there you can simply access it like Extras::Eupload.excel_upload from your console 从那里,您可以从控制台中像Extras::Eupload.excel_upload一样简单地访问它

You can create a new Rakefile and prepend it with the below, then you can have access to rails from anywhere: 您可以创建一个新的Rakefile并在其前面添加以下内容,然后可以从任何地方访问rails:

APP_PATH = File.expand_path('../../config/application',  __FILE__)
require File.expand_path('../../config/boot',  __FILE__)
require APP_PATH
# set Rails.env here if desired
Rails.application.require_environment!

create a rake file your_task.rake inside, /lib/tasks /lib/tasks创建一个rake文件your_task.rake

inside this your_task.rake : your_task.rake内部:

namespace :your_task_name do
  desc "Description About your task"
  task :task_name => :environment do
    # Write all your task here
  end

end

now run this task from terminal: 现在从终端运行此任务:

rake your_task_name:task_name

It's simple right. 这很简单。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM