Search code examples
rubyrhomobilerhodes

Rhomobile: Read txt file and show content Ruby


i want to open, read and show a txt file in my Rhomobile app. First, i want to show the complete content of the file. But here is my problem.

def text
fileName = File.join(Rho::RhoApplication::get_base_app_path(), '/app/test.txt')
    f = File.open(fileName, 'r')
    while line = f.gets
    puts line
    end
  f.close
    redirect :action => :index  
    end

the code read the txt file, but how can i call the method and show the results on a page. I don´t know whats the varaible is?

Please help me :) Thanks a lot!


Solution

  • If you only want to read the whole file, you can use this method:

    @file_content = File.read(fileName);
    

    You can assign the file's content to a instance variable (prefixed with an @) and show it in your view (*.html.erb or *.erb):

    File content: <%= @file_content %>
    

    Additionally, if you call redirect then your view won't be rendered and the user will be redirected to the specified action (index). So the code for the controller action should be this:

    def text
      @file_content = File.read(fileName);
      render action: 'text'
    end