Search code examples
rubyrubymotion

AFMotion HTTP GET request syntax for setting variable


My goal is to set an instance variable using AFMotion's AFMotion::HTTP.get method.

I've set up a Post model. I would like to have something like:

class Post
  ...
  def self.all
    response = AFMotion::HTTP.get("localhost/posts.json") 
    objects = JSON.parse(response)
    results = objects.map{|x| Post.new(x)}
  end
end

But according to the docs, AFMotion requires some sort of block syntax that looks and seems to behave like an async javascript callback. I am unsure how to use that.

I would like to be able to call

@posts = Post.all in the ViewController. Is this just a Rails dream? Thanks!


Solution

  • yeah, the base syntax is async, so you don't have to block the UI while you're waiting for the network to respond. The syntax is simple, place all the code you want to load in your block.

    class Post
      ...
      def self.all
        AFMotion::HTTP.get("localhost/posts.json") do |response|
          if result.success?
            p "You got JSON data"
            # feel free to parse this data into an instance var
            objects = JSON.parse(response)
            @results = objects.map{|x| Post.new(x)}
          elsif result.failure?
            p  result.error.localizedDescription
          end
    
        end
    
      end
    end
    

    Since you mentioned Rails, yeah, this is a lil different logic. You'll need to place the code you want to run (on completion) inside the async block. If it's going to change often, or has nothing to do with your Model, then pass in a &block to yoru method and use that to call back when it's done.

    I hope that helps!