Sha256: d8c460f77caebc4c52c74e5f8e3a6ca9d8b0643ef29cb8b8f2b8241dcbbb5ba6

Contents?: true

Size: 1.11 KB

Versions: 4

Compression:

Stored size: 1.11 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)
      m = line.match(/\* (.+)/)
      return m ? m[1] : nil
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
my_help-1.2.6 lib/my_help/org2hash.rb
my_help-1.2.5 lib/my_help/org2hash.rb
my_help-1.2.4p1 lib/my_help/org2hash.rb
my_help-1.2.4 lib/my_help/org2hash.rb