简体   繁体   中英

How to make an active job in ruby on rails to read json file then transfer data to database

I'm newbie here. I have problem, I build a web use Ruby on Rails. I want to get data from json file and then insert into database. data in json file can be increased at any time. So I should have a background job to run in certain intervals. I have read in Ruby documentation, and it said that I can use Active Job. But I still confuse to do that. What should I do step by step to make it real? or you guys can give me example?

Thanks anyway.

You can use ActiveJob

Active Job Setup

The Active Job adapter must be set to :sidekiq or it will simply use the default :inline.

This can be done in config/application.rb like this:

For example:

class Application < Rails::Application
  # ...
  config.active_job.queue_adapter = :sidekiq
end

Next, generate Job:

rails generate job Example

Sample JSON Data:

{
    "title"  :    "Ruby In Rails",
    "url"    :    "http://rubyinrails.com",
    "posts"  :    {
                    "1":"strftime-time-format-in-ruby",
                    "2":"what-is-gemset"
                  }
}

Will creates /app/jobs/example_job.rb

class ExampleJob < ActiveJob::Base
  # Set the Queue as Default
  queue_as :default

  def perform(*args)
    # Perform Job
    require 'json'

    # Open JSON File
    root = Rails.root.to_s       
    file = File.read('#{root}/data.json')


    # Parse Data from File
    data_hash = JSON.parse(file)

    # Do the SAVING and validation HERE...
    test = Sample.new
    test.title = data_hash['title']
    ......
    test.save


  end
end

Usage, ex. in Controller:

ExampleJob.perform_later args

Documentations Here

Or if you prefer to USE CRONJOB for that function:

For example make a file named " save_json.rb " inside lib/tasks/ in your Rails Application.

Code:

namespace :save_json do
  desc "..."
  task :execute => :environment do
    require 'json'

    # Open JSON File
    root = Rails.root.to_s       
    file = File.read('#{root}/data.json')


    #Parse Data from File
    data_hash = JSON.parse(file) 

    #Getting DATA

    data_hash['title']
     => "Ruby In Rails"
    data_hash.keys
     => ["title", "url", "posts"]
    data_hash['posts']
     => { "1" => "strftime-time-format-in-ruby", "2" => "what-is-gemset" }

    # Do the SAVING and validation HERE...
    test = Sample.new
    test.title = data_hash['title']
    ......
    test.save

end

Set Background Job function in crontab .

vi /etc/crontab

Code: For example every minute ....

*/1 * * * * cd /my_rails_app && bundle exec rake save_json:execute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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