Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
H

her

> 后端框架
Open source

Her is an ORM (Object Relational Mapper) that maps REST resources to Ruby objects. It is designed to build applications that are powered by a RESTful API instea

2.1K stars0 likes1 views
WebsiteGitHub

About

Her is an ORM (Object Relational Mapper) that maps REST resources to Ruby objects. It is designed to build applications that are powered by a RESTful API instea


Her is an ORM (Object Relational Mapper) that maps REST resources to Ruby objects.
It is designed to build applications that are powered by a RESTful API instead of a database.


Installation

In your Gemfile, add:

ruby
gem "her"

That’s it!

Usage

For a complete reference of all the methods you can use, check out the documentation.

First, you have to define which API your models will be bound to. For example, with Rails, you would create a new config/initializers/her.rb file with these lines:

ruby
# config/initializers/her.rb
Her::API.setup url: "https://api.example.com" do |c|
  # Request
  c.use Faraday::Request::UrlEncoded

  # Response
  c.use Her::Middleware::DefaultParseJSON

  # Adapter
  c.use Faraday::Adapter::NetHttp
end

And then to add the ORM behavior to a class, you just have to include Her::Model in it:

ruby
class User
  include Her::Model
end

After that, using Her is very similar to many ActiveRecord-like ORMs:

…

ActiveRecord-like methods

These are the basic ActiveRecord-like methods you can use with your models:

…

You can look into the her-example repository for a sample application using Her.

Middleware

Since Her relies on Faraday to send HTTP requests, you can choose the middleware used to handle requests and responses. Using the block in the setup call, you have access to Faraday’s connection object and are able to customize the middleware stack used on each request and response.

Authentication

Her doesn’t support authentication by default. However, it’s easy to implement one with request middleware. Using the setup block, we can add it to the middleware stack.

For example, to add a token header to your API requests in a Rails application, you could use the excellent request_store gem like this:

…

Now, each HTTP request made by Her will have the X-API-Token header.

Basic Http Authentication

Her can use basic http auth by adding a line to your initializer

ruby
# config/initializers/her.rb
Her::API.setup url: "https://api.example.com" do |c|
  # Request
  c.use Faraday::Request::BasicAuthentication, 'myusername', 'mypassword'
  c.use Faraday::Request::UrlEncoded

  # Response
  c.use Her::Middleware::DefaultParseJSON

  # Adapter
  c.use Faraday::Adapter::NetHttp
end

OAuth

Using the faraday_middleware and simple_oauth gems, it’s fairly easy to use OAuth authentication with Her.

In your Gemfile:

ruby
gem "her"
gem "faraday_middleware"
gem "simple_oauth"

In your Ruby code:

ruby
# Create an application on `https://dev.twitter.com/apps` to set these values
TWITTER_CREDENTIALS = {
  consumer_key: "",
  consumer_secret: "",
  token: "",
  token_secret: ""
}

Her::API.setup url: "https://api.twitter.com/1/" do |c|
  # Request
  c.use FaradayMiddleware::OAuth, TWITTER_CREDENTIALS

  # Response
  c.use Her::Middleware::DefaultParseJSON

  # Adapter
  c.use Faraday::Adapter::NetHttp
end

class Tweet
  include Her::Model
end

@tweets = Tweet.get("/statuses/home_timeline.json")

See the Authentication middleware section for an example of how to pass different credentials based on the current user.

Parsing JSON data

By default, Her handles JSON data. It expects the resource/collection data to be returned at the first level.

javascript
// The response of GET /users/1
{ "id" : 1, "name" : "Tobias Fünke" }

// The response of GET /users
[{ "id" : 1, "name" : "Tobias Fünke" }]

However, if you want Her to be able to parse the data from a single root element (usually based on the model name), you’ll have to use the parse_root_in_json method (See the JSON attributes-wrapping section).

Also, you can define your own parsing method using a response middleware. The middleware should set env[:body] to a hash with three symbol keys: :data, :errors and :metadata. The following code uses a custom middleware to parse the JSON data:

ruby
# Expects responses like:
#
#     {
#       "result": { "id": 1, "name": "Tobias Fünke" },
#       "errors": []
#     }
#
class MyCustomParser < Faraday::Response::Middleware
  def on_complete(env)
    json = MultiJson.load(env[:body], symbolize_keys: true)
    env[:body] = {
      data: json[:result],
      errors: json[:errors],
      metadata: json[:metadata]
    }
  end
end

Her::API.setup url: "https://api.example.com" do |c|
  # Response
  c.use MyCustomParser

  # Adapter
  c.use Faraday::Adapter::NetHttp
end

Caching

Again, using the faraday_middleware and memcached gems makes it very easy to cache requests and responses.

In your Gemfile:

ruby
gem "her"
gem "faraday_middleware"
gem "memcached"

In your Ruby code:

ruby
Her::API.setup url: "https://api.example.com" do |c|
  # Request
  c.use FaradayMiddleware::Caching, Memcached::Rails.new('127.0.0.1:11211')

  # Response
  c.use Her::Middleware::DefaultParseJSON

  # Adapter
  c.use Faraday::Adapter::NetHttp
end

class User
  include Her::Model
end

@user = User.find(1)
# GET "/users/1"

@user = User.find(1)
# This request will be fetched from memcached

Advanced Features

Here’s a list of several useful features available in Her.

Associations

Examples use this code:

ruby
class User
  include Her::Model
  has_many :comments
  has_one :role
  belongs_to :organization
end

class Comment
  include Her::Model
end

class Role
  include Her::Model
end

class Organization
  include Her::Model
end

Fetching data

You can define has_many, has_one and belongs_to associations in your models. The association data is handled in two different ways.

  1. If Her finds association data when parsing a resource, that data will be used to create the associated model objects on the resource.
  2. If no association data was included when parsing a resource, calling a method with the same name as the association will fetch the data (providing there’s an HTTP request available for it in the API).

For example, if there’s association data in the resource, no extra HTTP request is made when calling the #comments method and an array of resources is returned:

ruby
@user = User.find(1)
# GET "/users/1", response is:
# {
#   "id": 1,
#   "name": "George Michael Bluth",
#   "comments": [
#     { "id": 1, "text": "Foo" },
#     { "id": 2, "text": "Bar" }
#   ],
#   "role": { "id": 1, "name": "Admin" },
#   "organization": { "id": 2, "name": "Bluth Company" }
# }

@user.comments
# => [#<Comment id=1 text="Foo">, #<Comment id=2 text="Bar">]

@user.role
# => #<Role id=1 name="Admin">

@user.organization
# => #<Organization id=2 name="Bluth Company">

If there’s no association data in the resource, Her makes a HTTP request to retrieve the data.

ruby
@user = User.find(1)
# GET "/users/1", response is { "id": 1, "name": "George Michael Bluth", "organization_id": 2 }

# has_many association:
@user.comments
# GET "/users/1/comments"
# => [#<Comment id=1>, #<Comment id=2>]

@user.comments.where(approved: 1)
# GET "/users/1/comments?approved=1"
# => [#<Comment id=1>]

# has_one association:
@user.role
# GET "/users/1/role"
# => #<Role id=1>

# belongs_to association:
@user.organization
# (the organization id comes from :organization_id, by default)
# GET "/organizations/2"
# => #<Organization id=2>

Subsequent calls to #comments, #role and #organization will not trigger extra HTTP requests and will return the cached objects.

Creating data

You can use the association methods to build new objects and save them.

ruby
@user = User.find(1)
@user.comments.build(body: "Just a draft")
# => [#<Comment body="Just a draft" user_id=1>]

@user.comments.create(body: "Hello world.", user_id: 1)
# POST "/comments" with `body=Hello+world.&user_id=1`
# => [#<Comment id=3 body="Hello world." user_id=1>]

You can also explicitly request a new object via the API when using build. This is useful if you're dealing with default attributes.

ruby
class Comment
  include Her::Model
  request_new_object_on_build true
end

@user = User.find(1)
@user.comments.build(body: "Just a draft")
# GET "/users/1/comments/new" with `body=Just+a+draft.`
# => [#<Comment id=nil body="Just a draft" archived=false user_id=1>]

Notes about paths

Resources must always have all the required attributes to build their complete path. For example, if you have these models:

ruby
class User
  include Her::Model
  collection_path "organizations/:organization_id/users"
end

class Organization
  include Her::Model
  has_many :users
end

Her expects all User resources to have an :organization_id (or :_organization_id) attribute. Otherwise, calling mostly all methods, like User.all, will throw an exception like this one:

ruby
Her::Errors::PathError: Missing :_organization_id parameter to build the request path. Path is `organizations/:organization_id/users`. Parameters are `{ … }`.

Associations with custom attributes

Associations can also be made using custom attributes:

ruby
class User
  include Her::Model
  belongs_to :owns, class_name: "Organization"
end

class Organization
  include Her::Model
  has_many :owners, class_name: "User"
end

Validations

Her includes ActiveModel::Validations so you can declare validations the same way you do in Rails.

However, validations must be triggered manually — they are not run, for example, when calling #save on an object, or #create on a model class.

ruby
class User
  include Her::Model

  attributes :fullname, :email
  validates :fullname, presence: true
  validates :email, presence: true
end

@user = User.new(fullname: "Tobias Fünke")
@user.valid? # => false

@user.save
# POST "/users" with `fullname=Tobias+Fünke` will still be called, even if the user is not valid

Dirty attributes

Her includes ActiveModel::Dirty so you can keep track of the attributes that have changed in an object.

ruby
class User
  include Her::Model

  attributes :fullname, :email
end

@user = User.new(fullname: "Tobias Fünke")
@user.fullname_changed? # => true
@user.changes # => { :fullname => [nil, "Tobias Fünke"] }

@user.save
# POST "/users" with `fullname=Tobias+Fünke`

@user.fullname_changed? # => false
@user.changes # => {}

To update only the modified attributes specify :send_only_modified_attributes => true in the setup.

Callbacks

You can add before and after callbacks to your models that are triggered on specific actions. You can use symbols or blocks.

ruby
class User
  include Her::Model
  before_save :set_internal_id
  after_find { |u| u.fullname.upcase! }

  def set_internal_id
    self.internal_id = 42 # Will be passed in the HTTP request
  end
end

@user = User.create(fullname: "Tobias Fünke")
# POST "/users" with `fullname=Tobias+Fünke&internal_id=42`

@user = User.find(1)
@user.fullname # => "TOBIAS FUNKE"

The available callbacks are:

  • before_save
  • before_create
  • before_update
  • before_destroy
  • after_save
  • after_create
  • after_update
  • after_destroy
  • after_find
  • after_initialize

JSON attributes-wrapping

Her supports sending and parsing JSON data wrapped in a root element (to be compatible with Rails’ include_root_in_json setting), like so:

Sending

If you want to send all data to your API wrapped in a root element based on the model name.

ruby
class User

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyjson-dataormrailsruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架