Model Doesn’t Have To Be An ActiveRecord

It annoys me when a new Rails developer automatically assumes that all models are ActiveRecord. Here’s an example of a model in one of my applications where I’ve decided to put a class that retrieves the information from the web and behaves like a model. I could’ve put it in helper or module, but it seems appropriate to put it in a model. Obviously this object doesn’t have CRUD since it’s read-only and you can use parse method to get the results.

This model retrieves the history of NJ lottery results and provides it as an array. It also puts the results in a local file so that it doesn’t hit the website every incident. This is also useful when you don’t have a web service running on the provider server.

require 'net/http'

class WinningNumbers
  attr_accessor :number_history, :game

  def initialize(game)
    case game
    when "mega"
      @location = "/lottery/data/big.dat"
      @game = "mega"
    when "pick_6"
      @location = "/lottery/data/pick6.dat"
      @game = "pick_6"
    else
      @location = "/lottery/data/big.dat"
      @game = "mega"
    end
  end

  def fetch
    history = ""
    Net::HTTP.start( 'www.state.nj.us', 80 ) do |http|
    history = http.get( @location ).body
    end
    File.open(File.join(RAILS_ROOT, 'data', "#{@game}.dat"), 'w') do |file|
      history.split("\n").each do |l|
        file.puts l.split("%")[4..9].join(" ")
      end
    end
  end

  def parse
    open(File.join(RAILS_ROOT, 'data', "#{@game}.dat")) {|file| file.readlines }.each {|l| l.strip! }
  end

So there, don’t be afraid to create a model without ActiveRecord.

Comments

Leave a Reply

You must be logged in to post a comment.