# Divisional charts in Ruby on Rails, cached with Rails.cache

> Rails needs no gem to call AstroNode: `Net::HTTP` and `JSON` ship with Ruby. This page puts a 40-line client in `app/services`, reads the key from encrypted credentials, serves a navamsa chart from a controller and caches it, because the same birth always gives the same chart.

Source: https://astronode.dev/integrations/rails · Updated: 2026-12-05

**How this page was verified:** `app/services/astro_node.rb` was executed with plain `ruby` 4.0 (no Rails installed) against the in-memory API: the chart, the 10-minute ascendant change and the three errors below are its output. The initializer, controller and `Rails.cache` calls are Rails glue and were not run.

## The key: credentials first, ENV as a fallback

Run `bin/rails credentials:edit` and add the key under its own namespace. The file is encrypted with `config/master.key`, which is git-ignored; production needs `RAILS_MASTER_KEY` set instead. Hosts that only offer environment variables can use `ASTRONODE_API_KEY` - the initializer accepts either.

Inside `bin/rails credentials:edit`:

```yaml
astronode:
  api_key: aie_live_...
```

`config/initializers/astronode.rb`:

```ruby
ASTRONODE = AstroNode.new(
  api_key: Rails.application.credentials.dig(:astronode, :api_key) || ENV["ASTRONODE_API_KEY"],
  base_url: ENV.fetch("ASTRONODE_BASE_URL", "https://api.astronode.dev"),
)
```

## A Net::HTTP client in app/services

`app/services/astro_node.rb` - plain Ruby, no Rails dependency:

```ruby
require "net/http"
require "json"

class AstroNode
  class Error < StandardError
    attr_reader :status, :code

    def initialize(status, code, message)
      super("#{status} #{code}: #{message}")
      @status = status
      @code = code
    end
  end

  def initialize(api_key:, base_url: "https://api.astronode.dev")
    @api_key = api_key
    @base = URI(base_url)
  end

  # Divisional chart. division 9 = navamsa (the default), 10 = dasamsa, ...
  def varga(birth, division: 9)
    post("/v1/charts/varga", birth.merge(division: division))
  end

  private

  def post(path, body)
    req = Net::HTTP::Post.new(path, "Authorization" => "Bearer #{@api_key}",
                                    "Content-Type" => "application/json")
    req.body = JSON.generate(body)
    res = Net::HTTP.start(@base.host, @base.port, use_ssl: @base.scheme == "https",
                                                  open_timeout: 5, read_timeout: 15) do |http|
      http.request(req)
    end
    json = JSON.parse(res.body)
    unless res.is_a?(Net::HTTPSuccess)
      raise Error.new(res.code.to_i, json.dig("error", "code"), json.dig("error", "message"))
    end

    json.fetch("data")
  end
end
```

- `use_ssl:` is derived from the URL. `Net::HTTP.start` does not switch to TLS on its own because the port is 443; without it the request goes out as plain text to an HTTPS port.
- `read_timeout` defaults to 60 seconds in `Net::HTTP`. A Puma thread blocked that long is a thread not serving anyone else, so set it lower.
- The class raises one error type carrying the API's `code`, so callers can rescue `AstroNode::Error` and branch on `VALIDATION_ERROR`, `PLAN_REQUIRED` or `RATE_LIMITED`.

## The controller action, cached

`app/controllers/navamsa_controller.rb`:

```ruby
class NavamsaController < ApplicationController
  def show
    birth = {
      date: params.require(:date),
      time: params.require(:time),
      tz_offset_minutes: Integer(params.require(:tz_offset_minutes)),
      lat: Float(params.require(:lat)),
      lng: Float(params.require(:lng)),
    }
    division = Integer(params.fetch(:division, 9))

    key = ["astronode/varga", division, *birth.values].join(":")
    chart = Rails.cache.fetch(key, expires_in: 30.days) do
      ASTRONODE.varga(birth, division: division)
    end
    render json: chart
  rescue ArgumentError, TypeError
    render json: { error: "bad number in query string" }, status: :bad_request
  rescue AstroNode::Error => e
    render json: { error: e.code, message: e.message }, status: e.status == 400 ? :bad_request : :bad_gateway
  end
end
```

Query-string values are always strings in Rails, so `Integer(...)` and `Float(...)` do the casting - and raise on junk instead of quietly turning `"abc"` into `0` the way `to_i` would. Sent as a string, `lat` came back as `400 VALIDATION_ERROR: Request validation failed`.

*D9 for 15 Aug 1990, 06:40 IST, New Delhi (from the client run)*

| Planet | Navamsa sign | House |
| --- | --- | --- |
| Ascendant | Gemini | - |
| Sun | Pisces | 10 |
| Moon | Taurus | 12 |
| Jupiter | Leo | 3 |
| Venus | Virgo | 4 |
| Rahu / Ketu | Aries / Libra | 11 / 5 |

The cache key holds every input, including the minutes of the birth time. A navamsa spans 3°20′ of the zodiac, so the D9 ascendant changes roughly every quarter of an hour of clock time: the same birth at 06:50 returned **Cancer**, not Gemini. Keying on the date alone would serve one person's chart to another. Thirty days rather than forever lets an engine update reach cached users ([divisional charts](https://astronode.dev/guides/divisional-chart-calculation)).

## The mistakes that bite first

- **"Caching does nothing" in development.** The generated `config/environments/development.rb` uses `:null_store` unless `tmp/caching-dev.txt` exists, so every `Rails.cache.fetch` runs the block. Toggle it with `bin/rails dev:cache` before concluding the cache is broken - and expect every request to hit the API until you do.
- **A missing master key in production.** Without `RAILS_MASTER_KEY` (and without the ENV fallback) the credentials lookup returns `nil`, the header becomes `Bearer ` and every call is `401 UNAUTHORIZED: Missing or invalid Authorization header` - the exact message the client printed when run with no key.
- **Unsupported divisions.** `division: 13` returned `400 VALIDATION_ERROR` listing the accepted values: 2, 3, 7, 9, 10, 12, 16, 20, 24, 27, 30, 40, 45 and 60. Pass `all: true` instead of `division` to get every one of them in one response.

> **Note:** `POST /v1/charts/varga` needs the Hobby plan or above; a Free key gets `403 PLAN_REQUIRED` ([what that means](https://astronode.dev/docs/errors/plan-required)).

## Questions

**Which AstroNode endpoints does the Ruby on Rails example call?**

1 endpoint: Divisional Charts (Navamsa, D1-D60) (`POST /v1/charts/varga`).

**Was the Ruby on Rails code on this page actually run?**

`app/services/astro_node.rb` was executed with plain `ruby` 4.0 (no Rails installed) against the in-memory API: the chart, the 10-minute ascendant change and the three errors below are its output. The initializer, controller and `Rails.cache` calls are Rails glue and were not run.

## Endpoints

- [`POST /v1/charts/varga`](https://astronode.dev/capabilities/vedic/charts-varga) - Divisional Charts (Navamsa, D1-D60) API
