Share This Article
The facade pattern in Ruby and OOP is a standard way to simplify interfaces.
In Ruby, you provide a new API that should look simpler than the real API.
You can use this pattern to rewrite 3rd part API, as a wrapper API, or to build an API in front of your database.
For example:
class User
def initialize(name)
@name = name
end
def rename(new_name)
@name = new_name
end
def name
@name
end
end
# users API
class UserAPI
def initialize(user)
@user = user
end
def rename(new_name)
@user.rename(new_name)
end
end
user = User.new("jhon")
user_api = UserAPI.new(user)
user_api.rename("john")
user.name
# => "john"
How to Simplify an Existing API
You can use a facade to simplify the usage of a complex API.
You should create a new class that should have a simpler interface.
The new class uses the complex API behind the scenes.
For example:
# A complex API
class APIClient
def get(path, headers = {})
# request code goes here
end
def post(path, body, headers = {})
# request code goes here
end
end
# A facade that simplifies the API
class Client
def get(path)
APIClient.get(path)
end
def post(path, body)
APIClient.post(path, body)
end
end
client = Client.new
client.get("/todos")
client.post("/todos", { title: "Buy milk" })
You can use a facade to wrap an existing API and write a simpler one.
How to Create an API for your Database
You can use a facade to build an OOP API for your database objects.
The idea is that you write an object-oriented wrapper for your database.
For example:
# A complex database table
class User
end
# A facade to simplify the database table
class UserAPI
def get(id)
User.where(id: id).first
end
def create(user_attrs)
User.create(user_attrs)
end
end
user_api = UserAPI.new
user_api.get(1)
user_api.create(name: "jhon")
You can use a facade to build a great OOP API in front of any database.
Summary
In this article, you’ve learned the facade pattern and how to use it to simplify an API existence or create a new one.