rubymotionrubymotion-promotion

How to load RubyMotion table view cell data from file


I'm getting started with RubyMotion and ProMotion. I'm building a table view and I would like to move the data out into an external file to make it easier to manage. Here's what I have so far:

class MasterScreen < PM::TableScreen
  title 'States'

  def table_data
    [{
      title: "Northwest States",
      cells: [
        { title: "Oregon", action: :view_details, arguments: { state: @oregon }},
        { title: "Washington", action: :view_details, arguments: { state: @washington }}
      ]
    }]
  end

  def view_details
    open DetailScreen.new(nav_bar: true)
  end
end

I'd like to move the names of the states (basically the cell titles) into something like a YAML or JSON file that I can load and iterate over. How can I achieve something like this?


Update: I managed to figure out how to load text from a file.

First I added bubble-wrap to my Gemfile and ran bundle install. BubbleWrap provides the helper method App.resources_path.

In my_app/resources/states.txt I have a list of states, separated by new lines:

Oregon
Washington
Foobar

In my Table View Controller, I read the file and split the file into an array of lines.

class MasterScreen < PM::TableScreen
  title 'States'

  def on_load
    data = File.read("#{App.resources_path}/states.txt")
    @states = data.lines
  end

  def table_data
    [{
      title: "Northwest States",
      cells: @states.map do |state|
        {
          title: state,
          action: :view_details,
          arguments: { state: state }
        }
      end
    }]
  end

  def view_details(arguments)
    open DetailScreen.new(nav_bar: true, title: arguments[:state])
  end
end

This works, but it's only part of what I was trying to do. I would still like to use a structure like YAML to represent titles and subtitles. What would be the RubyMotion way to do this sort of thing?


Solution

  • Figured out how to do it. I came across a RubyMotion gem called motion-yaml. Simply add it to your Gemfile, add your YAML file to your resources directory, and use it like you would YAML in Ruby.

    data = YAML.load(File.read("#{App.resources_path}/my_yaml_file.yml"))
    

    Note: You will need to add bubble-wrap to your Gemfile in order to have the App.resources_path. I'm not sure if there is an easy way to do it without bubble-wrap.