Sha256: e7d014672afa2ef588f03289dc598e554bcf077589ca2d284d021d42999f64f9

Contents?: true

Size: 1.08 KB

Versions: 5

Compression:

Stored size: 1.08 KB

Contents

module MyHelp
  # get org and trans it to hash by FSM
  class Org2Hash
    attr_accessor :contents, :text
    # current_state => [  new_state,    action ]
    TRANSITIONS = {
      :header_read => {
        "* " => [:contents_read, :start_new_item],
        :default => [:header_read, :ignore],
      },
      :contents_read => {
        "* " => [:contents_read, :start_new_item],
        :default => [:contents_read, :add_contents],
      },
    }

    def initialize(org_text)
      @text = org_text
      @contents = Hash.new
      simple_fsm()
    end

    def simple_fsm()
      state = :header_read
      item = ""
      @text.split("\n").each do |line|
        next if line.size < 1
        state, action = TRANSITIONS[state][line[0..1]] ||
                        TRANSITIONS[state][:default]
        case action
        when :ignore
        when :start_new_item
          item = read_item(line)
          @contents[item] = ""
        when :add_contents
          @contents[item] += line + "\n"
        end
      end
    end

    def read_item(line)
      line.match(/\* (.+)/)[1]
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
my_help-1.2.3 lib/my_help/org2hash.rb
my_help-1.2.2 lib/my_help/org2hash.rb
my_help-1.2 lib/my_help/org2hash.rb
my_help-1.1a lib/my_help/org2hash.rb
my_help-1.1 lib/my_help/org2hash.rb