In this blog post, I am going to make you familiar with the process of integrating App42 BaaS with rails4. But before we proceed, if you haven’t used App42 BaaS in your rails application anytime before this, then please check out our previous blog post Using App42 Backend as a Service SDK in Ruby On Rails. Here are the steps to get started with the integration: To get going, first you need to create an application using below command: In the above command, I used –skip-active-record to avoid to generate ORM files as App42 BaaS will take care of your app’s Backend.
Now switch to your application directory and include App42_RUBY_SDK gem in your application Gemfile.
gem 'App42_RUBY_SDK'
Once you are done with it, run bundle update command which will update all your gem dependencies to their latest versions. Now it’s time to create two configuration files, which will load your App42 API and Secret key into your application and will create an instance of ServiceAPI.
First Create a YML file app42baas.yml inside the config folder of the application, which looks like:
development:
api_key: "your api key"
secret_key: "your secret key"
production:
api_key: "your api key"
secret_key: "your secret key"
Then create a second file in config/initializers folder e.g. app42_load.rb and paste the following code inside that app42_load.rb
require 'App42_RUBY_SDK'
APP_CONFIG = YAML.load_file("#{Rails.root}/config/app42baas.yml")[Rails.env]
$api = App42::ServiceAPI.new(APP_CONFIG['api_key'], APP_CONFIG['secret_key'] )
Now you can use $api object inside your application to get the instance of the particular API that you wish to build.
Let’s use User Service API to create user and get all users. To get started, we need to create a user controller using the below command: It creates user controller and respective views. Replace below code with existing user controller code
class UserController < ApplicationController
@@user_service = $api.buildUserService
def new
end
def index
@user_list = @@user_service.get_all_users
end
def create
begin
@@user_service.create_user(params['user_name'], params['password'], params['email'])
redirect_to user_index_path, notice: 'Thank you!, New user createed successfully.'
rescue Exception => e
redirect_to user_index_path, notice: "#{e.message}"
end
end
end
At the same time, you need to modify your views to create user and show user details.
/views/users/new.html.rb
<%= link_to "Add new User", user_new_path %>
<% unless @user_list.nil? %>
Name | |
<%= "#{user.userName}" %> | <%= "#{user.email}" %> |
Leave A Reply