ruby-on-railsparsingrails-activerecordparslet

Parse before storing in MVC


I'm getting started with parsing data and getting some structure from user supplied strings (mostly pulling out digits and city names).

I've run a bit of code in the ruby interpreter, and now I want to use that same code in a web application.

I'm struggling as to where in the code my parsing should be, or how it is structured.

My initial instinct was that it belongs in the model, because it is data logic. For example, does the entry have an integer, does it have two integers, does it have a city name, etc. etc.

However, my model would need to inherit both ActiveRecord, and Parslet (for the parsing), and Ruby apparently doesn't allow multiple inheritance.

My current model is looking like this

#concert model
require 'parslet'
class concert < Parlset::Parser
  attr_accessible :date, :time, :city_id, :band_id, :original_string

   rule(:integer) {match('[0-9]').repeat(1)}
   root(:integer)
end

Really not much there, but I think I'm stuck because I've got the structure wrong and don't know how to connect these two pieces.

I'm trying to store the original string, as well as components of the parsed data.


Solution

  • I think what you want is:

    #concert model
    require 'parslet'
    class concert < ActiveRecord::Base
      before_save :parse_fields
      attr_accessible :date, :time, :city_id, :band_id, :original_string
    
    
       rule(:integer) {match('[0-9]').repeat(1)}
       root(:integer)
    
      private
      def parse_fields
        date = Parlset::Parser.method_on_original_string_to_extract_date
        time = Parlset::Parser.method_on_original_string_to_extract_time
        city_id = Parlset::Parser.method_on_original_string_to_extract_city_id
        band_id = Parlset::Parser.method_on_original_string_to_extract_band_id
      end
    end