repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/spec/support/active_record.rb | spec/support/active_record.rb | require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => ":memory:"
)
ActiveRecord::Migration.verbose = false
DatabaseCleaner[:active_record].strategy = :transaction
ActiveRecord::Schema.define do
create_table :activity_feed_items, :force => true do |t|
t.string :user_id
t.string :nickname
t.string :type
t.string :title
t.text :body
t.timestamps
end
end
module ActivityFeed
module ActiveRecord
class Item < ::ActiveRecord::Base
self.table_name = 'activity_feed_items'
self.inheritance_column = nil
after_save :update_activity_feed
private
def update_activity_feed
ActivityFeed.update_item(self.user_id, self.id, self.created_at.to_i)
end
end
end
end | ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/spec/support/mongoid.rb | spec/support/mongoid.rb | require 'mongoid'
# If using Mongoid 2.x
# Mongoid.configure do |config|
# config.master = Mongo::Connection.new.db("activity_feed_gem_test")
# end
# If using Mongoid 3.x
Mongoid.load!("#{File.dirname(__FILE__)}/mongoid.yml", :test)
DatabaseCleaner[:mongoid].strategy = :truncation
module ActivityFeed
module Mongoid
class Item
include ::Mongoid::Document
include ::Mongoid::Timestamps
field :user_id, :type => String
validates_presence_of :user_id
field :nickname, :type => String
field :type, :type => String
field :title, :type => String
field :text, :type => String
field :url, :type => String
field :icon, :type=> String
field :sticky, :type=> Boolean
# If using Mongoid 2.x
# index :user_id
# If using Mongoid 3.x
index({ user_id: 1})
after_save :update_activity_feed
private
def update_activity_feed
ActivityFeed.update_item(self.user_id, self.id, self.created_at.to_i)
end
end
end
end | ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/spec/activity_feed/configuration_spec.rb | spec/activity_feed/configuration_spec.rb | require 'spec_helper'
describe ActivityFeed::Configuration do
describe '#configure' do
it 'should have default attributes' do
ActivityFeed.configure do |configuration|
expect(configuration.namespace).to eql('activity_feed')
expect(configuration.aggregate).to be_falsey
expect(configuration.aggregate_key).to eql('aggregate')
expect(configuration.page_size).to eql(25)
end
end
end
end | ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/spec/activity_feed/utility_spec.rb | spec/activity_feed/utility_spec.rb | require 'spec_helper'
describe ActivityFeed::Utility do
describe '#feed_key' do
it 'should return the correct key for the non-aggregate feed' do
expect(ActivityFeed.feed_key('david')).to eq('activity_feed:david')
end
it 'should return the correct key for an aggregate feed' do
expect(ActivityFeed.feed_key('david', true)).to eq('activity_feed:aggregate:david')
end
end
describe '#feederboard_for' do
it 'should create a leaderboard using an existing Redis connection' do
feederboard_david = ActivityFeed.feederboard_for('david')
feederboard_person = ActivityFeed.feederboard_for('person')
expect(feederboard_david).not_to be_nil
expect(feederboard_person).not_to be_nil
end
end
end | ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/spec/activity_feed/feed_spec.rb | spec/activity_feed/feed_spec.rb | require 'spec_helper'
describe ActivityFeed::Feed do
describe '#feed and #for' do
describe 'without aggregation' do
it 'should return an activity feed with the items correctly ordered' do
feed = ActivityFeed.feed('david', 1)
expect(feed.length).to eql(0)
add_items_to_feed('david')
[:feed, :for].each do |method|
feed = ActivityFeed.send(method, 'david', 1)
expect(feed.length).to eql(5)
expect(feed[0].to_i).to eql(5)
expect(feed[4].to_i).to eql(1)
end
end
end
describe 'with aggregation' do
it 'should return an aggregate activity feed with the items correctly ordered' do
feed = ActivityFeed.feed('david', 1, true)
expect(feed.length).to eql(0)
add_items_to_feed('david', 5, true)
feed = ActivityFeed.feed('david', 1, true)
expect(feed.length).to eql(5)
expect(feed[0].to_i).to eql(5)
expect(feed[4].to_i).to eql(1)
end
end
end
describe '#full_feed' do
describe 'without aggregation' do
it 'should return the full activity feed' do
feed = ActivityFeed.full_feed('david', false)
expect(feed.length).to eql(0)
add_items_to_feed('david', 30)
feed = ActivityFeed.full_feed('david', false)
expect(feed.length).to eql(30)
expect(feed[0].to_i).to eql(30)
expect(feed[29].to_i).to eql(1)
end
end
describe 'with aggregation' do
it 'should return the full activity feed' do
feed = ActivityFeed.full_feed('david', true)
expect(feed.length).to eql(0)
add_items_to_feed('david', 30, true)
feed = ActivityFeed.full_feed('david', true)
expect(feed.length).to eql(30)
expect(feed[0].to_i).to eql(30)
expect(feed[29].to_i).to eql(1)
end
end
end
describe '#feed_between_timestamps and #between' do
describe 'without aggregation' do
it 'should return activity feed items between the starting and ending timestamps' do
feed = ActivityFeed.feed_between_timestamps('david', Time.local(2012, 6, 19, 4, 43, 0).to_i, Time.local(2012, 6, 19, 8, 16, 0).to_i, false)
expect(feed.length).to eql(0)
Timecop.travel(Time.local(2012, 6, 19, 4, 0, 0))
ActivityFeed.update_item('david', 1, Time.now.to_i)
Timecop.travel(Time.local(2012, 6, 19, 4, 30, 0))
ActivityFeed.update_item('david', 2, Time.now.to_i)
Timecop.travel(Time.local(2012, 6, 19, 5, 30, 0))
ActivityFeed.update_item('david', 3, Time.now.to_i)
Timecop.travel(Time.local(2012, 6, 19, 6, 37, 0))
ActivityFeed.update_item('david', 4, Time.now.to_i)
Timecop.travel(Time.local(2012, 6, 19, 8, 17, 0))
ActivityFeed.update_item('david', 5, Time.now.to_i)
Timecop.return
[:feed_between_timestamps, :between].each do |method|
feed = ActivityFeed.send(method, 'david', Time.local(2012, 6, 19, 4, 43, 0).to_i, Time.local(2012, 6, 19, 8, 16, 0).to_i, false)
expect(feed.length).to eql(2)
expect(feed[0].to_i).to eql(4)
expect(feed[1].to_i).to eql(3)
end
end
end
describe 'with aggregation' do
it 'should return activity feed items between the starting and ending timestamps' do
feed = ActivityFeed.feed_between_timestamps('david', Time.local(2012, 6, 19, 4, 43, 0).to_i, Time.local(2012, 6, 19, 8, 16, 0).to_i, true)
expect(feed.length).to eql(0)
Timecop.travel(Time.local(2012, 6, 19, 4, 0, 0))
ActivityFeed.update_item('david', 1, Time.now.to_i, true)
Timecop.travel(Time.local(2012, 6, 19, 4, 30, 0))
ActivityFeed.update_item('david', 2, Time.now.to_i, true)
Timecop.travel(Time.local(2012, 6, 19, 5, 30, 0))
ActivityFeed.update_item('david', 3, Time.now.to_i, true)
Timecop.travel(Time.local(2012, 6, 19, 6, 37, 0))
ActivityFeed.update_item('david', 4, Time.now.to_i, true)
Timecop.travel(Time.local(2012, 6, 19, 8, 17, 0))
ActivityFeed.update_item('david', 5, Time.now.to_i, true)
Timecop.return
[:feed_between_timestamps, :between].each do |method|
feed = ActivityFeed.send(method, 'david', Time.local(2012, 6, 19, 4, 43, 0).to_i, Time.local(2012, 6, 19, 8, 16, 0).to_i, true)
expect(feed.length).to eql(2)
expect(feed[0].to_i).to eql(4)
expect(feed[1].to_i).to eql(3)
end
end
end
end
describe '#total_pages_in_feed and #total_pages' do
describe 'without aggregation' do
it 'should return the correct number of pages in the activity feed' do
expect(ActivityFeed.total_pages_in_feed('david')).to eql(0)
expect(ActivityFeed.total_pages('david')).to eql(0)
add_items_to_feed('david', Leaderboard::DEFAULT_PAGE_SIZE + 1)
expect(ActivityFeed.total_pages_in_feed('david')).to eql(2)
expect(ActivityFeed.total_pages('david')).to eql(2)
end
end
describe 'with aggregation' do
it 'should return the correct number of pages in the aggregate activity feed' do
expect(ActivityFeed.total_pages_in_feed('david', true)).to eql(0)
expect(ActivityFeed.total_pages('david', true)).to eql(0)
add_items_to_feed('david', Leaderboard::DEFAULT_PAGE_SIZE + 1, true)
expect(ActivityFeed.total_pages_in_feed('david', true)).to eql(2)
expect(ActivityFeed.total_pages('david', true)).to eql(2)
end
end
describe 'changing page_size parameter' do
it 'should return the correct number of pages in the activity feed' do
expect(ActivityFeed.total_pages_in_feed('david', false, 4)).to eql(0)
expect(ActivityFeed.total_pages('david', false, 4)).to eql(0)
add_items_to_feed('david', 25)
expect(ActivityFeed.total_pages_in_feed('david', false, 4)).to eql(7)
expect(ActivityFeed.total_pages('david', false, 4)).to eql(7)
end
end
end
describe '#remove_feeds and #remove' do
it 'should remove the activity feeds for a given user ID' do
add_items_to_feed('david', Leaderboard::DEFAULT_PAGE_SIZE + 1, true)
expect(ActivityFeed.total_items_in_feed('david')).to eql(Leaderboard::DEFAULT_PAGE_SIZE + 1)
expect(ActivityFeed.total_items_in_feed('david', true)).to eql(Leaderboard::DEFAULT_PAGE_SIZE + 1)
ActivityFeed.remove_feeds('david')
expect(ActivityFeed.total_items_in_feed('david')).to eql(0)
expect(ActivityFeed.total_items_in_feed('david', true)).to eql(0)
end
end
describe '#total_items_in_feed and #total_items' do
describe 'without aggregation' do
it 'should return the correct number of items in the activity feed' do
expect(ActivityFeed.total_items_in_feed('david')).to eql(0)
expect(ActivityFeed.total_items('david')).to eql(0)
add_items_to_feed('david', Leaderboard::DEFAULT_PAGE_SIZE + 1)
expect(ActivityFeed.total_items_in_feed('david')).to eql(Leaderboard::DEFAULT_PAGE_SIZE + 1)
expect(ActivityFeed.total_items('david')).to eql(Leaderboard::DEFAULT_PAGE_SIZE + 1)
end
end
describe 'with aggregation' do
it 'should return the correct number of items in the aggregate activity feed' do
expect(ActivityFeed.total_items_in_feed('david', true)).to eql(0)
expect(ActivityFeed.total_items('david', true)).to eql(0)
add_items_to_feed('david', Leaderboard::DEFAULT_PAGE_SIZE + 1, true)
expect(ActivityFeed.total_items_in_feed('david', true)).to eql(Leaderboard::DEFAULT_PAGE_SIZE + 1)
expect(ActivityFeed.total_items('david', true)).to eql(Leaderboard::DEFAULT_PAGE_SIZE + 1)
end
end
end
describe '#trim_feed' do
describe 'without aggregation' do
it 'should trim activity feed items between the starting and ending timestamps' do
[:trim_feed, :trim].each do |method|
Timecop.travel(Time.local(2012, 6, 19, 4, 0, 0))
ActivityFeed.update_item('david', 1, Time.now.to_i)
Timecop.travel(Time.local(2012, 6, 19, 4, 30, 0))
ActivityFeed.update_item('david', 2, Time.now.to_i)
Timecop.travel(Time.local(2012, 6, 19, 5, 30, 0))
ActivityFeed.update_item('david', 3, Time.now.to_i)
Timecop.travel(Time.local(2012, 6, 19, 6, 37, 0))
ActivityFeed.update_item('david', 4, Time.now.to_i)
Timecop.travel(Time.local(2012, 6, 19, 8, 17, 0))
ActivityFeed.update_item('david', 5, Time.now.to_i)
Timecop.return
ActivityFeed.send(method, 'david', Time.local(2012, 6, 19, 4, 29, 0).to_i, Time.local(2012, 6, 19, 8, 16, 0).to_i)
feed = ActivityFeed.feed('david', 1)
expect(feed.length).to eql(2)
expect(feed[0].to_i).to eql(5)
expect(feed[1].to_i).to eql(1)
end
end
end
describe 'with aggregation' do
it 'should trim activity feed items between the starting and ending timestamps' do
[:trim_feed, :trim].each do |method|
Timecop.travel(Time.local(2012, 6, 19, 4, 0, 0))
ActivityFeed.update_item('david', 1, Time.now.to_i, true)
Timecop.travel(Time.local(2012, 6, 19, 4, 30, 0))
ActivityFeed.update_item('david', 2, Time.now.to_i, true)
Timecop.travel(Time.local(2012, 6, 19, 5, 30, 0))
ActivityFeed.update_item('david', 3, Time.now.to_i, true)
Timecop.travel(Time.local(2012, 6, 19, 6, 37, 0))
ActivityFeed.update_item('david', 4, Time.now.to_i, true)
Timecop.travel(Time.local(2012, 6, 19, 8, 17, 0))
ActivityFeed.update_item('david', 5, Time.now.to_i, true)
Timecop.return
ActivityFeed.send(method, 'david', Time.local(2012, 6, 19, 4, 29, 0).to_i, Time.local(2012, 6, 19, 8, 16, 0).to_i, true)
feed = ActivityFeed.feed('david', 1, true)
expect(feed.length).to eql(2)
expect(feed[0].to_i).to eql(5)
expect(feed[1].to_i).to eql(1)
end
end
end
end
describe '#trim_to_size' do
describe 'without aggregation' do
it 'should allow you to trim activity feed items to a given size' do
add_items_to_feed('david')
expect(ActivityFeed.total_items('david')).to eql(5)
ActivityFeed.trim_to_size('david', 3)
expect(ActivityFeed.total_items('david')).to eql(3)
end
end
describe 'with aggregation' do
it 'should allow you to trim activity feed items to a given size' do
add_items_to_feed('david', 5, true)
expect(ActivityFeed.total_items('david', true)).to eql(5)
ActivityFeed.trim_to_size('david', 3, true)
expect(ActivityFeed.total_items('david', true)).to eql(3)
end
end
end
describe 'ORM or ODM loading' do
describe 'ActiveRecord' do
it 'should be able to load an item via ActiveRecord when requesting a feed' do
ActivityFeed.items_loader = Proc.new do |ids|
ActivityFeed::ActiveRecord::Item.find(ids)
end
feed = ActivityFeed.feed('david', 1)
expect(feed.length).to eql(0)
item = ActivityFeed::ActiveRecord::Item.create(
:user_id => 'david',
:nickname => 'David Czarnecki',
:type => 'some_activity',
:title => 'Great activity',
:body => 'This is text for the feed item'
)
feed = ActivityFeed.feed('david', 1)
expect(feed.length).to eql(1)
expect(feed[0]).to eq(item)
end
end
describe 'Mongoid' do
it 'should be able to load an item via Mongoid when requesting a feed' do
ActivityFeed.items_loader = Proc.new do |ids|
ActivityFeed::Mongoid::Item.find(ids)
end
feed = ActivityFeed.feed('david', 1)
expect(feed.length).to eql(0)
item = ActivityFeed::Mongoid::Item.create(
:user_id => 'david',
:nickname => 'David Czarnecki',
:type => 'some_activity',
:title => 'Great activity',
:text => 'This is text for the feed item',
:url => 'http://url.com'
)
feed = ActivityFeed.feed('david', 1)
expect(feed.length).to eql(1)
expect(feed[0]).to eq(item)
end
end
end
describe '#expire_feed, #expire_in and #expire_feed_in' do
it 'should set an expiration on an activity feed using #expire_feed' do
add_items_to_feed('david', Leaderboard::DEFAULT_PAGE_SIZE)
ActivityFeed.expire_feed('david', 10)
ActivityFeed.redis.ttl(ActivityFeed.feed_key('david')).tap do |ttl|
expect(ttl).to be > 1
expect(ttl).to be <= 10
end
end
it 'should set an expiration on an activity feed using #expire_in' do
add_items_to_feed('david', Leaderboard::DEFAULT_PAGE_SIZE)
ActivityFeed.expire_in('david', 10)
ActivityFeed.redis.ttl(ActivityFeed.feed_key('david')).tap do |ttl|
expect(ttl).to be > 1
expect(ttl).to be <= 10
end
end
it 'should set an expiration on an activity feed using #expire_feed_in' do
add_items_to_feed('david', Leaderboard::DEFAULT_PAGE_SIZE)
ActivityFeed.expire_feed_in('david', 10)
ActivityFeed.redis.ttl(ActivityFeed.feed_key('david')).tap do |ttl|
expect(ttl).to be > 1
expect(ttl).to be <= 10
end
end
end
describe '#expire_feed_at and #expire_at' do
it 'should set an expiration timestamp on an activity feed using #expire_feed' do
add_items_to_feed('david', Leaderboard::DEFAULT_PAGE_SIZE)
ActivityFeed.expire_feed_at('david', (Time.now + 10).to_i)
ActivityFeed.redis.ttl(ActivityFeed.feed_key('david')).tap do |ttl|
expect(ttl).to be > 1
expect(ttl).to be <= 10
end
end
it 'should set an expiration timestamp on an activity feed using #expire_at' do
add_items_to_feed('david', Leaderboard::DEFAULT_PAGE_SIZE)
ActivityFeed.expire_at('david', (Time.now + 10).to_i)
ActivityFeed.redis.ttl(ActivityFeed.feed_key('david')).tap do |ttl|
expect(ttl).to be > 1
expect(ttl).to be <= 10
end
end
end
end | ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/spec/activity_feed/item_spec.rb | spec/activity_feed/item_spec.rb | require 'spec_helper'
require 'active_support/core_ext/date_time/conversions'
describe ActivityFeed::Item do
describe '#update_item' do
describe 'without aggregation' do
it 'should correctly build an activity feed' do
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_falsey
ActivityFeed.update_item('david', 1, Time.now.to_i)
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_truthy
end
end
describe 'with aggregation' do
it 'should correctly build an activity feed with an aggregate activity_feed' do
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_falsey
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david', true))).to be_falsey
ActivityFeed.update_item('david', 1, Time.now.to_i, true)
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_truthy
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david', true))).to be_truthy
end
end
end
describe '#add_item' do
describe 'without aggregation' do
it 'should correctly build an activity feed' do
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_falsey
ActivityFeed.add_item('david', 1, Time.now.to_i)
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_truthy
end
end
end
describe '#aggregate_item' do
it 'should correctly add an item into an aggregate activity feed' do
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_falsey
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david', true))).to be_falsey
ActivityFeed.aggregate_item('david', 1, Time.now.to_i)
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_falsey
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david', true))).to be_truthy
end
end
describe '#remove_item' do
describe 'without aggregation' do
it 'should remove an item from an activity feed' do
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_falsey
expect(ActivityFeed.redis.zcard(ActivityFeed.feed_key('david'))).to eql(0)
ActivityFeed.update_item('david', 1, Time.now.to_i)
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_truthy
expect(ActivityFeed.redis.zcard(ActivityFeed.feed_key('david'))).to eql(1)
ActivityFeed.remove_item('david', 1)
expect(ActivityFeed.redis.zcard(ActivityFeed.feed_key('david'))).to eql(0)
end
end
describe 'with aggregation' do
it 'should remove an item from an activity feed and the aggregate feed' do
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_falsey
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david', true))).to be_falsey
expect(ActivityFeed.redis.zcard(ActivityFeed.feed_key('david'))).to eql(0)
expect(ActivityFeed.redis.zcard(ActivityFeed.feed_key('david', true))).to eql(0)
ActivityFeed.update_item('david', 1, Time.now.to_i, true)
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david'))).to be_truthy
expect(ActivityFeed.redis.exists(ActivityFeed.feed_key('david', true))).to be_truthy
expect(ActivityFeed.redis.zcard(ActivityFeed.feed_key('david'))).to eql(1)
expect(ActivityFeed.redis.zcard(ActivityFeed.feed_key('david', true))).to eql(1)
ActivityFeed.remove_item('david', 1)
expect(ActivityFeed.redis.zcard(ActivityFeed.feed_key('david'))).to eql(0)
expect(ActivityFeed.redis.zcard(ActivityFeed.feed_key('david', true))).to eql(0)
end
end
end
describe '#check_item?' do
describe 'without aggregation' do
it 'should return whether or not an item exists in the feed' do
ActivityFeed.aggregate = false
expect(ActivityFeed.check_item?('david', 1)).to be_falsey
ActivityFeed.add_item('david', 1, Time.now.to_i)
expect(ActivityFeed.check_item?('david', 1)).to be_truthy
end
end
describe 'with aggregation' do
it 'should return whether or not an item exists in the feed' do
ActivityFeed.aggregate = true
expect(ActivityFeed.check_item?('david', 1, true)).to be_falsey
ActivityFeed.add_item('david', 1, Time.now.to_i)
expect(ActivityFeed.check_item?('david', 1, true)).to be_truthy
end
end
end
end | ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/lib/activity_feed.rb | lib/activity_feed.rb | require 'activity_feed/configuration'
require 'activity_feed/item'
require 'activity_feed/feed'
require 'activity_feed/utility'
require 'activity_feed/version'
require 'leaderboard'
module ActivityFeed
extend Configuration
extend Item
extend Feed
extend Utility
end | ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/lib/activity_feed/feed.rb | lib/activity_feed/feed.rb | module ActivityFeed
module Feed
# Retrieve a page from the activity feed for a given +user_id+. You can configure
# +ActivityFeed.items_loader+ with a Proc to retrieve items from, for example,
# your ORM (e.g. ActiveRecord) or your ODM (e.g. Mongoid), and have the page
# returned with loaded items rather than item IDs.
#
# @param user_id [String] User ID.
# @param page [int] Page in the feed to be retrieved.
# @param aggregate [boolean, false] Whether to retrieve the aggregate feed for +user_id+.
#
# @return page from the activity feed for a given +user_id+.
def feed(user_id, page, aggregate = ActivityFeed.aggregate)
feederboard = ActivityFeed.feederboard_for(user_id, aggregate)
feed_items = feederboard.leaders(page, :page_size => ActivityFeed.page_size)
load_feed_items(feed_items)
end
alias_method :for, :feed
# Retrieve the entire activity feed for a given +user_id+. You can configure
# +ActivityFeed.items_loader+ with a Proc to retrieve items from, for example,
# your ORM (e.g. ActiveRecord) or your ODM (e.g. Mongoid), and have the page
# returned with loaded items rather than item IDs.
#
# @param user_id [String] User ID.
# @param aggregate [boolean, false] Whether to retrieve the aggregate feed for +user_id+.
#
# @return the full activity feed for a given +user_id+.
def full_feed(user_id, aggregate = ActivityFeed.aggregate)
feederboard = ActivityFeed.feederboard_for(user_id, aggregate)
feed_items = feederboard.leaders(1, :page_size => feederboard.total_members)
load_feed_items(feed_items)
end
# Retrieve a page from the activity feed for a given +user_id+ between a
# +starting_timestamp+ and an +ending_timestamp+. You can configure
# +ActivityFeed.items_loader+ with a Proc to retrieve items from, for example,
# your ORM (e.g. ActiveRecord) or your ODM (e.g. Mongoid), and have the feed data
# returned with loaded items rather than item IDs.
#
# @param user_id [String] User ID.
# @param starting_timestamp [int] Starting timestamp between which items in the feed are to be retrieved.
# @param ending_timestamp [int] Ending timestamp between which items in the feed are to be retrieved.
# @param aggregate [boolean, false] Whether to retrieve items from the aggregate feed for +user_id+.
#
# @return feed items from the activity feed for a given +user_id+ between the +starting_timestamp+ and +ending_timestamp+.
def feed_between_timestamps(user_id, starting_timestamp, ending_timestamp, aggregate = ActivityFeed.aggregate)
feederboard = ActivityFeed.feederboard_for(user_id, aggregate)
feed_items = feederboard.members_from_score_range(starting_timestamp, ending_timestamp)
load_feed_items(feed_items)
end
alias_method :between, :feed_between_timestamps
# Return the total number of pages in the activity feed.
#
# @param user_id [String] User ID.
# @param aggregate [boolean, false] Whether to check the total number of pages in the aggregate activity feed or not.
# @param page_size [int, ActivityFeed.page_size] Page size to be used in calculating the total number of pages in the activity feed.
#
# @return the total number of pages in the activity feed.
def total_pages_in_feed(user_id, aggregate = ActivityFeed.aggregate, page_size = ActivityFeed.page_size)
ActivityFeed.feederboard_for(user_id, aggregate).total_pages_in(ActivityFeed.feed_key(user_id, aggregate), page_size)
end
alias_method :total_pages, :total_pages_in_feed
# Return the total number of items in the activity feed.
#
# @param user_id [String] User ID.
# @param aggregate [boolean, false] Whether to check the total number of items in the aggregate activity feed or not.
#
# @return the total number of items in the activity feed.
def total_items_in_feed(user_id, aggregate = ActivityFeed.aggregate)
ActivityFeed.feederboard_for(user_id, aggregate).total_members
end
alias_method :total_items, :total_items_in_feed
# Remove the activity feeds for a given +user_id+.
#
# @param user_id [String] User ID.
def remove_feeds(user_id)
ActivityFeed.redis.multi do |transaction|
transaction.del(ActivityFeed.feed_key(user_id, false))
transaction.del(ActivityFeed.feed_key(user_id, true))
end
end
# Trim an activity feed between two timestamps.
#
# @param user_id [String] User ID.
# @param starting_timestamp [int] Starting timestamp after which activity feed items will be cut.
# @param ending_timestamp [int] Ending timestamp before which activity feed items will be cut.
# @param aggregate [boolean, false] Whether or not to trim the aggregate activity feed or not.
def trim_feed(user_id, starting_timestamp, ending_timestamp, aggregate = ActivityFeed.aggregate)
ActivityFeed.feederboard_for(user_id, aggregate).remove_members_in_score_range(starting_timestamp, ending_timestamp)
end
alias_method :trim, :trim_feed
# Trim an activity feed to a given size.
#
# @param user_id [String] User ID.
# @param size [int] Number of items to keep in the activity feed.
# @param aggregate [boolean, false] Whether or not to trim the aggregate activity feed or not.
def trim_to_size(user_id, size, aggregate = ActivityFeed.aggregate)
ActivityFeed.feederboard_for(user_id, aggregate).remove_members_outside_rank(size)
end
alias_method :trim_to, :trim_to_size
# Expire an activity feed after a set number of seconds.
#
# @param user_id [String] User ID.
# @param seconds [int] Number of seconds after which the activity feed will be expired.
# @param aggregate [boolean, false] Whether or not to expire the aggregate activity feed or not.
def expire_feed(user_id, seconds, aggregate = ActivityFeed.aggregate)
ActivityFeed.redis.expire(ActivityFeed.feed_key(user_id, aggregate), seconds)
end
alias_method :expire_in, :expire_feed
alias_method :expire_feed_in, :expire_feed
# Expire an activity feed at a given timestamp.
#
# @param user_id [String] User ID.
# @param timestamp [int] Timestamp after which the activity feed will be expired.
# @param aggregate [boolean, false] Whether or not to expire the aggregate activity feed or not.
def expire_feed_at(user_id, timestamp, aggregate = ActivityFeed.aggregate)
ActivityFeed.redis.expireat(ActivityFeed.feed_key(user_id, aggregate), timestamp)
end
alias_method :expire_at, :expire_feed_at
private
# Load feed items from the `ActivityFeed.items_loader` if available,
# otherwise return the individual members from the feed items.
#
# @param feed_items [Array] Array of hash feed items as `[{:member=>"5", :rank=>1, :score=>1373564960.0}, ...]`
#
# @return Array of feed items
def load_feed_items(feed_items)
feed_item_ids = feed_items.collect { |feed_item| feed_item[:member] }
if ActivityFeed.items_loader
ActivityFeed.items_loader.call(feed_item_ids)
else
feed_item_ids
end
end
end
end | ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/lib/activity_feed/version.rb | lib/activity_feed/version.rb | module ActivityFeed
VERSION = '3.1.0'
end
| ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/lib/activity_feed/item.rb | lib/activity_feed/item.rb | module ActivityFeed
module Item
# Add or update an item in the activity feed for a given +user_id+.
#
# @param user_id [String] User ID.
# @param item_id [String] Item ID.
# @param timestamp [int] Timestamp for the item being added or updated.
# @param aggregate [boolean, false] Whether to add or update the item in the aggregate feed for +user_id+.
def update_item(user_id, item_id, timestamp, aggregate = ActivityFeed.aggregate)
feederboard = ActivityFeed.feederboard_for(user_id, false)
feederboard.rank_member(item_id, timestamp)
if aggregate
feederboard = ActivityFeed.feederboard_for(user_id, true)
feederboard.rank_member(item_id, timestamp)
end
end
alias_method :add_item, :update_item
# Specifically aggregate an item in the activity feed for a given +user_id+.
# This is useful if you are going to background the process of populating
# a user's activity feed from friend's activities.
#
# @param user_id [String] User ID.
# @param item_id [String] Item ID.
# @param timestamp [int] Timestamp for the item being added or updated.
def aggregate_item(user_id, item_id, timestamp)
feederboard = ActivityFeed.feederboard_for(user_id, true)
feederboard.rank_member(item_id, timestamp)
end
# Remove an item from the activity feed for a given +user_id+. This
# will also remove the item from the aggregate activity feed for the
# user.
#
# @param user_id [String] User ID.
# @param item_id [String] Item ID.
def remove_item(user_id, item_id)
feederboard = ActivityFeed.feederboard_for(user_id, false)
feederboard.remove_member(item_id)
feederboard = ActivityFeed.feederboard_for(user_id, true)
feederboard.remove_member(item_id)
end
# Check to see if an item is in the activity feed for a given +user_id+.
#
# @param user_id [String] User ID.
# @param item_id [String] Item ID.
# @param aggregate [boolean, false] Whether or not to check the aggregate activity feed.
def check_item?(user_id, item_id, aggregate = ActivityFeed.aggregate)
feederboard_individual = ActivityFeed.feederboard_for(user_id, false)
feederboard_aggregate = ActivityFeed.feederboard_for(user_id, true)
aggregate ? feederboard_aggregate.check_member?(item_id) : feederboard_individual.check_member?(item_id)
end
end
end | ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/lib/activity_feed/utility.rb | lib/activity_feed/utility.rb | module ActivityFeed
module Utility
# Feed key for a +user_id+ composed of:
#
# Feed: +ActivityFeed.namespace:user_id+
# Aggregate feed: +ActivityFeed.namespace:ActivityFeed.aggregate_key:user_id+
#
# @return feed key.
def feed_key(user_id, aggregate = ActivityFeed.aggregate)
aggregate ?
"#{ActivityFeed.namespace}:#{ActivityFeed.aggregate_key}:#{user_id}" :
"#{ActivityFeed.namespace}:#{user_id}"
end
# Retrieve a reference to the activity feed for a given +user_id+.
#
# @param user_id [String] User ID.
# @param aggregate [boolean, false] Whether to retrieve the aggregate feed for +user_id+ or not.
#
# @return reference to the activity feed for a given +user_id+.
def feederboard_for(user_id, aggregate = ActivityFeed.aggregate)
::Leaderboard.new(feed_key(user_id, aggregate), ::Leaderboard::DEFAULT_OPTIONS, {:redis_connection => ActivityFeed.redis})
end
end
end | ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
agoragames/activity_feed | https://github.com/agoragames/activity_feed/blob/4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5/lib/activity_feed/configuration.rb | lib/activity_feed/configuration.rb | module ActivityFeed
# Configuration settings for ActivityFeed.
module Configuration
# Redis instance.
attr_accessor :redis
# Proc that will be called for loading items from an
# ORM (e.g. ActiveRecord) or ODM (e.g. Mongoid). Proc
# will be called with the IDs of the items from the feed.
attr_accessor :items_loader
# ActivityFeed namespace for Redis.
attr_writer :namespace
# Indicates whether or not aggregation is enabled.
attr_writer :aggregate
# Key used in Redis for an individual's aggregate feed.
attr_writer :aggregate_key
# Page size to be used when paging through the activity feed.
attr_writer :page_size
# Yield self to be able to configure ActivityFeed with
# block-style configuration.
#
# Example:
#
# ActivityFeed.configure do |configuration|
# configuration.redis = Redis.new
# configuration.namespace = 'activity_feed'
# configuration.aggregate = false
# configuration.aggregate_key = 'aggregate'
# configuration.page_size = 25
# end
def configure
yield self
end
# ActivityFeed namespace for Redis.
#
# @return the ActivityFeed namespace or the default of 'activity_feed' if not set.
def namespace
@namespace ||= 'activity_feed'
end
# Indicates whether or not aggregation is enabled.
#
# @return whether or not aggregation is enabled or the default of +false+ if not set.
def aggregate
@aggregate ||= false
end
# Key used in Redis for an individul's aggregate feed.
#
# @return the key used in Redis for an individual's aggregate feed or the default of 'aggregate' if not set.
def aggregate_key
@aggregate_key ||= 'aggregate'
end
# Default page size.
#
# @return the page size or the default of 25 if not set.
def page_size
@page_size ||= 25
end
end
end | ruby | MIT | 4f93a29b69b70d6ae1dbbdb7ce3da83d4f413aa5 | 2026-01-04T17:47:31.631220Z | false |
companionstudio/instagram-token-agent | https://github.com/companionstudio/instagram-token-agent/blob/02fec49788a3a73dc1ad7207743d5fb01ce713d9/app.rb | app.rb | require 'dotenv'
require 'bundler'
Dotenv.load
Bundler.require
require_relative 'lib/instagram_token_agent'
class App < Sinatra::Base
register Sinatra::ActiveRecordExtension
register Sinatra::CrossOrigin
# Nicer debugging in dev mode
configure :development do
require 'pry'
require "better_errors"
use BetterErrors::Middleware
BetterErrors.application_root = __dir__
end
# -------------------------------------------------
# Overall configuration - done here rather than yml files to reduce dependencies
# -------------------------------------------------
configure do
set :app_name, ENV['APP_NAME'] # The app needs to know its own name/url.
set :app_url, ENV['APP_URL'] || "https://#{settings.app_name}.herokuapp.com"
enable :cross_origin
disable :show_exceptions
enable :raise_errors
set :help_pages, !(ENV['HIDE_HELP_PAGES']) || false # Whether to display the welcome pages or not
set :allow_origin, ENV['ALLOWED_DOMAINS'] ? ENV['ALLOWED_DOMAINS'].split(' ').map{|d| "https://#{d}"} : settings.app_url # Check for a whitelist of domains, otherwise allow the herokapp domain
set :allow_methods, [:get, :options] # Only allow GETs and OPTION requests
set :allow_credentials, false # We have no need of credentials!
set :default_starting_token, 'copy_token_here' # The 'Deploy to Heroku' button sets this environment value
set :js_constant_name, ENV['JS_CONSTANT_NAME'] ||'InstagramToken' # The name of the constant used in the JS snippet
# scheduled mode would be more efficient, but currently doesn't work
# because Temporize free accounts don't support dates more than 7 days in the future
set :token_refresh_mode, ENV['REFRESH_MODE'] || :cron # cron | scheduled
set :token_expiry_buffer, 2 * 24 * 60 * 60 # 2 days before expiry
set :token_refresh_frequency, ENV['REFRESH_FREQUENCY'].to_s || :weekly # daily, weekly, monthly
set :refresh_endpoint, 'https://graph.instagram.com/refresh_access_token' # The endpoint to hit to extend the token
set :user_endpoint, 'https://graph.instagram.com/me' # The endpoint to hit to fetch user profile
set :media_endpoint, 'https://graph.instagram.com/me/media' # The endpoint to hit to fetch the user's media
set :refresh_webhook, (ENV['TEMPORIZE_URL'] ? true : false) # Check if Temporize is configured
set :webhook_secret, ENV['WEBHOOK_SECRET'] # The secret value used to sign external, incoming requests
end
# Make sure everything is set up before we try to do anything else
before do
ensure_configuration!
end
# Switch for the help pages
unless settings.help_pages?
['/', '/status', '/setup'].each do |help_page|
before help_page do
halt 204
end
end
end
# -------------------------------------------------
# The 'hello world' pages
# @TODO: allow an environment var to turn this off, as it's never needed once in production
# -------------------------------------------------
# The home page
get '/' do
haml(:index, layout: :'layouts/default')
end
# Requested by the index page, this checks the status of the
# refresh task and talks to Instagram to ensure everything's set up.
get '/status' do
@client ||= InstagramTokenAgent::Client.new(settings)
check_refresh_job
haml(:status, layout: nil)
end
# Show the setup page - mostly for dev, this is shown automatically in production
get '/setup' do
app_info
haml(:setup, layout: :'layouts/default')
end
get '/instafeed' do
haml(:instafeed, layout: :'layouts/default')
end
# Allow a manual refresh, but only if the previous attempt failed
post '/refresh' do
if InstagramTokenAgent::Store.success?
halt 204
else
client = InstagramTokenAgent::Client.new(settings)
client.refresh
redirect '/setup'
end
end
# -------------------------------------------------
# The Token API
# This is a good candidate for a Sinatra namespace, but sinatra-contrib needs updating
# -------------------------------------------------
#Some clients will make an OPTIONS pre-flight request before doing CORS requests
options '/token' do
cross_origin
response.headers["Allow"] = settings.allow_methods
response.headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Cache-Control, Accept"
204 #'No Content'
end
# Return the token itself
# Formats:
# - .js
# - .json
# - plain text (default)
#
get '/token:format?' do
# Tokens remain active even after refresh, so we can set the cache up close to FB's expiry
cache_control :public, max_age: InstagramTokenAgent::Store.expires - Time.now - settings.token_expiry_buffer
cross_origin
response_body = case params['format']
when '.js'
content_type 'application/javascript'
@js_constant_name = params[:const] || settings.js_constant_name;
erb(:'javascript/snippet.js')
when '.json'
content_type 'application/json'
json(token: InstagramTokenAgent::Store.value)
else
InstagramTokenAgent::Store.value
end
etag Digest::SHA1.hexdigest(response_body + (response.headers['Access-Control-Allow-Origin'] || '*'))
response_body
end
# -------------------------------------------------
# Webhook endpoints
#
# Used by the Temporize scheduling service to trigger a refresh externally
# -------------------------------------------------
if settings.refresh_webhook?
post "/hooks/refresh/:signature" do
client = InstagramTokenAgent::Client.new(settings)
if client.check_signature? params[:signature]
client.refresh
else
halt 403
end
end
end
# -------------------------------------------------
# Error pages
# -------------------------------------------------
not_found do
haml(:not_found, layout: :'layouts/default')
end
error do
haml(:error, layout: :'layouts/default')
end
helpers do
# Provide some info sourced from the app.json file
def app_info
@app_info ||= InstagramTokenAgent::AppInfo.info
end
# Check that the configuration looks right to continue
def configured?
return false unless check_allowed_domains
return false unless check_starting_token
true
end
# Show the setup screen if we're not yet ready to go.
def ensure_configuration!
halt haml(:setup, layout: :'layouts/default') unless configured?
end
# Find the date of the next refresh job
def next_refresh_date
if next_job = temporize_client.next_job
DateTime.parse(next_job['next']).strftime('%b %-d %Y, %-l:%M%P %Z')
else
nil
end
end
def check_allowed_domains
ENV['ALLOWED_DOMAINS'].present? and !ENV['ALLOWED_DOMAINS'].match(/\*([^\.]|$)/) # Disallow including * in the allow list
end
def check_starting_token
ENV['STARTING_TOKEN'] != settings.default_starting_token
end
def check_token_status
InstagramTokenAgent::Store.success? and InstagramTokenAgent::Store.value.present?
end
def latest_instagram_response
JSON.pretty_generate(JSON.parse(InstagramTokenAgent::Store.response_body))
end
end
private
# Check that a job has been scheduled
def check_refresh_job
return unless temporize_client.jobs.empty?
temporize_client.update!
end
def temporize_client
raise 'Refresh webhooks are not enabled' unless settings.refresh_webhook?
@temporize_client ||= Temporize::Scheduler.new(settings)
end
end
| ruby | MIT | 02fec49788a3a73dc1ad7207743d5fb01ce713d9 | 2026-01-04T17:47:31.319073Z | false |
companionstudio/instagram-token-agent | https://github.com/companionstudio/instagram-token-agent/blob/02fec49788a3a73dc1ad7207743d5fb01ce713d9/lib/instagram_token_agent.rb | lib/instagram_token_agent.rb | require_relative 'instagram_token_agent/version'
require_relative 'instagram_token_agent/store'
require_relative 'instagram_token_agent/client'
require_relative 'temporize/scheduler'
module InstagramTokenAgent
module AppInfo
def self.info
if File.exist?("#{Dir.pwd}/app.json")
file = File.read("#{Dir.pwd}/app.json")
data = JSON.parse(file)
else
{}
end
end
end
end
| ruby | MIT | 02fec49788a3a73dc1ad7207743d5fb01ce713d9 | 2026-01-04T17:47:31.319073Z | false |
companionstudio/instagram-token-agent | https://github.com/companionstudio/instagram-token-agent/blob/02fec49788a3a73dc1ad7207743d5fb01ce713d9/lib/instagram_token_agent/version.rb | lib/instagram_token_agent/version.rb | module InstagramTokenAgent
VERSION = '1.0.3'.freeze
end
| ruby | MIT | 02fec49788a3a73dc1ad7207743d5fb01ce713d9 | 2026-01-04T17:47:31.319073Z | false |
companionstudio/instagram-token-agent | https://github.com/companionstudio/instagram-token-agent/blob/02fec49788a3a73dc1ad7207743d5fb01ce713d9/lib/instagram_token_agent/store.rb | lib/instagram_token_agent/store.rb | module InstagramTokenAgent
# Handle interfacing with the database, updating and retrieving values
class Store
# Execute the given SQL and params
def self.execute(sql, params = [])
binds = params.map{|p| [nil, p]}
ActiveRecord::Base.connection_pool.with_connection { |con| con.exec_query(sql, 'sql', binds) }
end
# Fetch the value row data and memoize
# This doesn't check if the token has expired - we'll let the client sort
# that out with Instagram.
#
# @return Proc
def self.data
row = execute('SELECT value, expires_at, created_at, success, response_body FROM tokens LIMIT 1').to_a[0]
@data ||= OpenStruct.new({
value: row['value'],
success: row['success'],
response_body: row['response_body'],
expires: row['expires_at'],
created: row['created_at']
})
end
# Update the token value in the store
# This assumes there's only ever a single row in the table
# The initial insert is done via the setup task.
def self.update(value, expires, success = true, response_body = nil)
execute('UPDATE tokens SET value = $1, expires_at = $2, success = $3, response_body = $4', [value, expires, success, response_body])
end
#Accessors for the token data
def self.value
data.value
end
def self.expires
data.expires
end
def self.success?
data.success == true
end
def self.response_body
data.response_body
end
def self.created
data.created
end
end
end
| ruby | MIT | 02fec49788a3a73dc1ad7207743d5fb01ce713d9 | 2026-01-04T17:47:31.319073Z | false |
companionstudio/instagram-token-agent | https://github.com/companionstudio/instagram-token-agent/blob/02fec49788a3a73dc1ad7207743d5fb01ce713d9/lib/instagram_token_agent/client.rb | lib/instagram_token_agent/client.rb | # Handles connecting to the basic display API
module InstagramTokenAgent
class Client
include HTTParty
attr_accessor :config
def initialize(settings)
@config = settings
end
# Does the provided signature match?
def check_signature?(check_signature)
check_signature == signature
end
# Fetch a fresh token from the instagram API
#
# @return Boolean indicating success or failure
def refresh
response = get(
config.refresh_endpoint,
query: query_params(grant_type: 'ig_refresh_token'),
headers: {"User-Agent" => "Instagram Token Agent"}
)
if response.success?
Store.update(response['access_token'], Time.now + response['expires_in'], true, nil)
# If we're working with single-use webhooks, schedule a job for the period [token_expiry_buffer] before expiry.
if config.refresh_webhook? and config.token_refresh_mode == :cron
scheduler = Temporize::Scheduler.new(config)
scheduler.queue_refresh((Time.now + response['expires_in'] - config.token_expiry_buffer), signature)
end
true
else
Store.update(ENV['STARTING_TOKEN'], Time.now, false, response.body)
false
end
end
def username
get(config.user_endpoint, query: query_params(fields: 'username'))['username']
end
def media
response = get(config.media_endpoint, query: query_params(fields: 'media_url'))
# Ew. This is gross
if response.success?
JSON.parse(response.body)['data'][0]['media_url']
else
nil
end
end
# The HMAC'd secret + initial token value
# It would be better to hash the current token value, but this won't work with recurring jobs, since
# the value needs to stay consistent.
def signature
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha1'), config.webhook_secret, ENV['STARTING_TOKEN'])
end
private
def get(*opts)
self.class.get(*opts)
end
def query_params(extra_params = {})
{access_token: Store.value}.merge(extra_params)
end
end
end
| ruby | MIT | 02fec49788a3a73dc1ad7207743d5fb01ce713d9 | 2026-01-04T17:47:31.319073Z | false |
companionstudio/instagram-token-agent | https://github.com/companionstudio/instagram-token-agent/blob/02fec49788a3a73dc1ad7207743d5fb01ce713d9/lib/temporize/scheduler.rb | lib/temporize/scheduler.rb | # Interface with Temporize's cron add-on for Heroku,
# This takes care of scheduling the refresh job for the future when a new expiry is known.
module Temporize
class Scheduler
include HTTParty
format :json
attr_accessor :config
base_uri "#{ENV['TEMPORIZE_URL']}/v1"
def initialize(settings)
@config = settings
end
# Extract the auth details from the URL, since HTTParty doesn't like them by default
def credentials
if basic_auth = URI.parse(Temporize::Scheduler.base_uri).userinfo
username, password = basic_auth.split(':')
{:username => username, :password => password}
end
end
# Wipe any existing jobs and create a new one
def update!
clear_all!
client = InstagramTokenAgent::Client.new(config)
queue_refresh(InstagramTokenAgent::Store.expires - config.token_expiry_buffer, client.signature)
end
#Queue a job to refresh the token at the specified time and date
def queue_refresh(time, signature)
hook_url = CGI::escape("#{config.app_url}/hooks/refresh/#{signature}")
schedule = CGI::escape(if config.token_refresh_mode == :scheduled
time.utc.iso8601
else
case config.token_refresh_frequency
when :daily
'0 0 * * ?' # Midnight every day
when :monthly
'0 0 1 * ?' # First day of each month
else
'0 0 * * ?' # Every Sunday
end
end)
Temporize::Scheduler.post("/events/#{schedule}/#{hook_url}", basic_auth: credentials).success?
end
# List all the jobs
def jobs
Temporize::Scheduler.get('/events', basic_auth: credentials)
end
# Get an individual job
def job(id)
Temporize::Scheduler.get("/events/#{id}", basic_auth: credentials)
end
# Find the next job
def next_job
job(jobs.first)
end
# Delete all upcoming jobs
def clear_all!
jobs.each do |id|
Temporize::Scheduler.delete("/events/#{id}", basic_auth: credentials)
end
end
end
end
| ruby | MIT | 02fec49788a3a73dc1ad7207743d5fb01ce713d9 | 2026-01-04T17:47:31.319073Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/spec/spec_helper.rb | spec/spec_helper.rb | require "pry"
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
MODELS = File.join(File.dirname(__FILE__), "app/models")
SUPPORT = File.join(File.dirname(__FILE__), "support")
$LOAD_PATH.unshift(MODELS)
$LOAD_PATH.unshift(SUPPORT)
require 'streama'
require 'mongoid'
require 'rspec'
require 'database_cleaner'
LOGGER = Logger.new($stdout)
DatabaseCleaner.strategy = :truncation
def database_id
ENV["CI"] ? "mongoid_#{Process.pid}" : "mongoid_test"
end
Mongoid.configure do |config|
config.connect_to(database_id)
end
Dir[ File.join(MODELS, "*.rb") ].sort.each do |file|
name = File.basename(file, ".rb")
autoload name.camelize.to_sym, name
end
require File.join(MODELS,"mars","user.rb")
Dir[ File.join(SUPPORT, "*.rb") ].each do |file|
require File.basename(file)
end
RSpec.configure do |config|
config.include RSpec::Matchers
config.mock_with :rspec
config.before(:each) do
DatabaseCleaner.start
Mongoid::IdentityMap.clear
end
config.after(:each) do
DatabaseCleaner.clean
end
config.after(:suite) do
if ENV["CI"]
Mongoid::Threaded.sessions[:default].drop
end
end
end
| ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/spec/app/models/activity.rb | spec/app/models/activity.rb | class Activity
include Streama::Activity
activity :new_photo do
actor :user, :cache => [:full_name]
object :photo, :cache => [:file]
target_object :album, :cache => [:title]
end
activity :new_photo_without_cache do
actor :user
object :photo
target_object :album
end
activity :new_comment do
actor :user, :cache => [:full_name]
object :photo
end
activity :new_tag do
actor :user, :cache => [:full_name]
object :photo
end
activity :new_mars_photo do
actor :user, :cache => [:full_name], :class_name => 'Mars::User'
object :photo
target_object :album, :cache => [:title]
end
end
| ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/spec/app/models/photo.rb | spec/app/models/photo.rb | class Photo
include Mongoid::Document
include Mongoid::Attributes::Dynamic
field :file
end
| ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/spec/app/models/no_mongoid.rb | spec/app/models/no_mongoid.rb | class NoMongoid
include Streama::Actor
field :full_name
def followers
self.class.all
end
end | ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/spec/app/models/album.rb | spec/app/models/album.rb | class Album
include Mongoid::Document
field :title
end | ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/spec/app/models/user.rb | spec/app/models/user.rb | class User
include Mongoid::Document
include Streama::Actor
field :full_name
def friends
self.class.all
end
def followers
self.class.all
end
end | ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/spec/app/models/mars/user.rb | spec/app/models/mars/user.rb | # encoding: utf-8
module Mars
class User
include Mongoid::Document
include Streama::Actor
field :full_name
def followers
self.class.all
end
end
end
| ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/spec/lib/activity_spec.rb | spec/lib/activity_spec.rb | require 'spec_helper'
describe "Activity" do
let(:photo) { Photo.create(:file => "image.jpg") }
let(:album) { Album.create(:title => "A test album") }
let(:user) { User.create(:full_name => "Christos") }
let(:mars_user) { Mars::User.create(:full_name => "Mars User") }
describe ".activity" do
it "registers and return a valid definition" do
@definition = Activity.activity(:test_activity) do
actor :user, :cache => [:full_name]
object :photo, :cache => [:file]
target_object :album, :cache => [:title]
end
@definition.is_a?(Streama::Definition).should be true
end
end
describe "#publish" do
before :each do
@send_to = []
2.times { |n| @send_to << User.create(:full_name => "Custom Receiver #{n}") }
5.times { |n| User.create(:full_name => "Receiver #{n}") }
end
it "pushes activity to receivers" do
@activity = Activity.publish(:new_photo, {:actor => user, :object => photo, :target_object => album, :receivers => @send_to})
@activity.receivers.size.should == 2
end
context "when activity not cached" do
it "pushes activity to receivers" do
@activity = Activity.publish(:new_photo_without_cache, {:actor => user, :object => photo, :target_object => album, :receivers => @send_to})
@activity.receivers.size.should == 2
end
end
it "overrides the recievers if option passed" do
@activity = Activity.publish(:new_photo, {:actor => user, :object => photo, :target_object => album, :receivers => @send_to})
@activity.receivers.size.should == 2
end
context "when republishing"
before :each do
@actor = user
@activity = Activity.publish(:new_photo, {:actor => @actor, :object => photo, :target_object => album})
@activity.publish
end
it "updates metadata" do
@actor.full_name = "testing"
@actor.save
@activity.publish
@activity.actor['full_name'].should eq "testing"
end
end
describe ".publish" do
it "creates a new activity" do
activity = Activity.publish(:new_photo, {:actor => user, :object => photo, :target_object => album})
activity.should be_an_instance_of Activity
end
it " creates a new activity when actor has namespace" do
activity = Activity.publish(:new_mars_photo, {:actor => mars_user, :object => photo, :target_object => album})
activity.should be_an_instance_of Activity
end
end
describe "#refresh" do
before :each do
@user = user
@activity = Activity.publish(:new_photo, {:actor => @user, :object => photo, :target_object => album})
end
it "reloads instances and updates activities stored data" do
@activity.save
@activity = Activity.last
expect do
@user.update_attribute(:full_name, "Test")
@activity.refresh_data
end.to change{ @activity.load_instance(:actor).full_name}.from("Christos").to("Test")
end
end
describe "#load_instance" do
before :each do
@activity = Activity.publish(:new_photo, {:actor => user, :object => photo, :target_object => album})
@activity = Activity.last
end
it "loads an actor instance" do
@activity.load_instance(:actor).should be_instance_of User
end
it "loads an object instance" do
@activity.load_instance(:object).should be_instance_of Photo
end
it "loads a target instance" do
@activity.load_instance(:target_object).should be_instance_of Album
end
end
end
| ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/spec/lib/definition_spec.rb | spec/lib/definition_spec.rb | require 'spec_helper'
describe "Definition" do
let(:definition_dsl) do
dsl = Streama::DefinitionDSL.new(:new_photo)
dsl.actor(:user, :cache => [:id, :full_name])
dsl.object(:photo, :cache => [:id, :full_name])
dsl.target_object(:album, :cache => [:id, :name, :full_address])
dsl
end
describe '#initialize' do
before(:all) do
@definition_dsl = definition_dsl
@definition = Streama::Definition.new(@definition_dsl)
end
it "assigns @actor" do
@definition.actor.has_key?(:user).should be true
end
it "assigns @object" do
@definition.object.has_key?(:photo).should be true
end
it "assigns @target" do
@definition.target_object.has_key?(:album).should be true
end
end
describe '.register' do
it "registers a definition and return new definition" do
Streama::Definition.register(definition_dsl).is_a?(Streama::Definition).should eq true
end
it "returns false if invalid definition" do
Streama::Definition.register(false).should be false
end
end
describe '.registered' do
it "returns registered definitions" do
Streama::Definition.register(definition_dsl)
Streama::Definition.registered.size.should be > 0
end
end
describe '.find' do
it "returns the definition by name" do
Streama::Definition.find(:new_photo).name.should eq :new_photo
end
it "raises an exception if invalid activity" do
lambda { Streama::Definition.find(:unknown_activity) }.should raise_error Streama::Errors::InvalidActivity
end
end
end
| ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/spec/lib/actor_spec.rb | spec/lib/actor_spec.rb | require 'spec_helper'
describe "Actor" do
let(:photo) { Photo.create(:comment => "I'm interested") }
let(:album) { Album.create(:title => "A test album") }
let(:user) { User.create(:full_name => "Christos") }
it "raises an exception if the class is not a mongoid document" do
lambda { NoMongoid.new }.should raise_error Streama::Errors::NotMongoid
end
describe "#publish_activity" do
before :each do
2.times { |n| User.create(:full_name => "Receiver #{n}") }
end
it "pushes activity to receivers" do
activity = user.publish_activity(:new_photo, :object => photo, :target_object => album)
activity.receivers.size == 6
end
it "pushes to a defined stream" do
activity = user.publish_activity(:new_photo, :object => photo, :target_object => album, :receivers => :friends)
activity.receivers.size == 6
end
end
describe "#activity_stream" do
before :each do
user.publish_activity(:new_photo, :object => photo, :target_object => album)
user.publish_activity(:new_comment, :object => photo)
u = User.create(:full_name => "Other User")
u.publish_activity(:new_photo, :object => photo, :target_object => album)
u.publish_activity(:new_tag, :object => photo)
end
it "retrieves the stream for an actor" do
user.activity_stream.size.should eq 4
end
it "retrieves the stream and filters to a particular activity type" do
user.activity_stream(:type => :new_photo).size.should eq 2
end
it "retrieves the stream and filters to a couple particular activity types" do
user.activity_stream(:type => [:new_tag, :new_comment]).size.should eq 2
end
end
describe "#published_activities" do
before :each do
user.publish_activity(:new_photo, :object => photo, :target_object => album)
user.publish_activity(:new_comment, :object => photo)
user.publish_activity(:new_tag, :object => photo)
u = User.create(:full_name => "Other User")
u.publish_activity(:new_photo, :object => photo, :target_object => album)
end
it "retrieves published activities for the actor" do
user.published_activities.size.should eq 3
end
it "retrieves and filters published activities by type for the actor" do
user.published_activities(:type => :new_photo).size.should eq 1
end
it "retrieves and filters published activities by a couple types for the actor" do
user.published_activities(:type => [:new_comment, :new_tag]).size.should eq 2
end
end
end
| ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/spec/lib/definition_dsl_spec.rb | spec/lib/definition_dsl_spec.rb | require 'spec_helper'
describe "Definition" do
let(:definition_dsl) {Streama::DefinitionDSL.new(:new_enquiry)}
it "initializes with name" do
definition_dsl.attributes[:name].should eq :new_enquiry
end
it "adds an actor to the definition" do
dsl = definition_dsl
dsl.actor(:user, :cache => [:id, :full_name])
dsl.attributes[:actor].should eq :user => { :cache=>[:id, :full_name] }
end
it "adds multiple actors to the definition" do
dsl = definition_dsl
dsl.actor(:user, :cache => [:id, :full_name])
dsl.actor(:company, :cache => [:id, :name])
dsl.attributes[:actor].should eq :user => { :cache=>[:id, :full_name] }, :company => { :cache=>[:id, :name] }
end
it "adds an object to the definition" do
dsl = definition_dsl
dsl.object(:listing, :cache => [:id, :title])
dsl.attributes[:object].should eq :listing => { :cache=>[:id, :title] }
end
it "adds a target to the definition" do
dsl = definition_dsl
dsl.target_object(:company, :cache => [:id, :name])
dsl.attributes[:target_object].should eq :company => { :cache=>[:id, :name] }
end
end
| ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/lib/streama.rb | lib/streama.rb | require "mongoid"
require "streama/version"
require "streama/actor"
require "streama/activity"
require "streama/definition"
require "streama/definition_dsl"
require "streama/errors" | ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/lib/streama/version.rb | lib/streama/version.rb | module Streama
VERSION = "0.3.8"
end
| ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/lib/streama/definition_dsl.rb | lib/streama/definition_dsl.rb | module Streama
class DefinitionDSL
attr_reader :attributes
def initialize(name)
@attributes = {
:name => name.to_sym,
:actor => {},
:object => {},
:target_object => {}
}
end
delegate :[], :to => :@attributes
def self.data_methods(*args)
args.each do |method|
define_method method do |*args|
class_sym = if class_name = args[1].try(:delete,:class_name)
class_name.underscore.to_sym
else
args[0].is_a?(Symbol) ? args[0] : args[0].class.to_sym
end
@attributes[method].store(class_sym, args[1])
end
end
end
data_methods :actor, :object, :target_object
end
end
| ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/lib/streama/errors.rb | lib/streama/errors.rb | module Streama
module Errors
class StreamaError < StandardError
end
class InvalidActivity < StreamaError
end
# This error is raised when an object isn't defined
# as an actor, object or target
#
# Example:
#
# <tt>InvalidField.new('field_name')</tt>
class InvalidData < StreamaError
attr_reader :message
def initialize message
@message = "Invalid Data: #{message}"
end
end
# This error is raised when trying to store a field that doesn't exist
#
# Example:
#
# <tt>InvalidField.new('field_name')</tt>
class InvalidField < StreamaError
attr_reader :message
def initialize message
@message = "Invalid Field: #{message}"
end
end
class ActivityNotSaved < StreamaError
end
class NoFollowersDefined < StreamaError
end
class NotMongoid < StreamaError
end
end
end | ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/lib/streama/actor.rb | lib/streama/actor.rb | module Streama
module Actor
extend ActiveSupport::Concern
included do
raise Errors::NotMongoid, "Must be included in a Mongoid::Document" unless self.ancestors.include? Mongoid::Document
cattr_accessor :activity_klass
end
module ClassMethods
def activity_class(klass)
self.activity_klass = klass.to_s
end
end
# Publishes the activity to the receivers
#
# @param [ Hash ] options The options to publish with.
#
# @example publish an activity with a object and target
# current_user.publish_activity(:enquiry, :object => @enquiry, :target => @listing)
#
def publish_activity(name, options={})
options[:receivers] = self.send(options[:receivers]) if options[:receivers].is_a?(Symbol)
activity = activity_class.publish(name, {:actor => self}.merge(options))
end
def activity_stream(options = {})
activity_class.stream_for(self, options)
end
def published_activities(options = {})
activity_class.stream_of(self, options)
end
def activity_class
@activity_klass ||= activity_klass ? activity_klass.classify.constantize : ::Activity
end
end
end | ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/lib/streama/activity.rb | lib/streama/activity.rb | module Streama
module Activity
extend ActiveSupport::Concern
included do
include Mongoid::Document
include Mongoid::Timestamps
field :verb, :type => Symbol
field :actor
field :object
field :target_object
field :receivers, :type => Array
index({ 'actor._id' => 1, 'actor._type' => 1 })
index({ 'object._id' => 1, 'object._type' => 1 })
index({ 'target_object._id' => 1, 'target_object._type' => 1 })
index({ 'receivers.id' => 1, 'receivers.type' => 1 })
validates_presence_of :actor, :verb
before_save :assign_data
end
module ClassMethods
# Defines a new activity type and registers a definition
#
# @param [ String ] name The name of the activity
#
# @example Define a new activity
# activity(:enquiry) do
# actor :user, :cache => [:full_name]
# object :enquiry, :cache => [:subject]
# target_object :listing, :cache => [:title]
# end
#
# @return [Definition] Returns the registered definition
def activity(name, &block)
definition = Streama::DefinitionDSL.new(name)
definition.instance_eval(&block)
Streama::Definition.register(definition)
end
# Publishes an activity using an activity name and data
#
# @param [ String ] verb The verb of the activity
# @param [ Hash ] data The data to initialize the activity with.
#
# @return [Streama::Activity] An Activity instance with data
def publish(verb, data)
receivers = data.delete(:receivers)
new({:verb => verb}.merge(data)).publish(:receivers => receivers)
end
def stream_for(actor, options={})
query = {:receivers => {'$elemMatch' => {:id => actor.id, :type => actor.class.to_s}}}
query.merge!({:verb.in => [*options[:type]]}) if options[:type]
self.where(query).desc(:created_at)
end
def stream_of(actor, options={})
query = {'actor.id' => actor.id, 'actor.type' => actor.class.to_s}
query.merge!({:verb.in => [*options[:type]]}) if options[:type]
self.where(query).desc(:created_at)
end
end
# Publishes the activity to the receivers
#
# @param [ Hash ] options The options to publish with.
#
def publish(options = {})
actor = load_instance(:actor)
self.receivers = (options[:receivers] || actor.followers).map { |r| { :id => r.id, :type => r.class.to_s } }
self.save
self
end
# Returns an instance of an actor, object or target
#
# @param [ Symbol ] type The data type (actor, object, target) to return an instance for.
#
# @return [Mongoid::Document] document A mongoid document instance
def load_instance(type)
(data = self.read_attribute(type)).is_a?(Hash) ? data['type'].to_s.camelcase.constantize.find(data['id']) : data
end
def refresh_data
assign_data
save(:validates_presence_of => false)
end
protected
def assign_data
[:actor, :object, :target_object].each do |type|
next unless object = load_instance(type)
class_sym = object.class.name.underscore.to_sym
raise Errors::InvalidData.new(class_sym) unless definition.send(type).has_key?(class_sym)
hash = {'id' => object.id, 'type' => object.class.name}
if fields = definition.send(type)[class_sym].try(:[],:cache)
fields.each do |field|
raise Errors::InvalidField.new(field) unless object.respond_to?(field)
hash[field.to_s] = object.send(field)
end
end
write_attribute(type, hash)
end
end
def definition
@definition ||= Streama::Definition.find(verb)
end
end
end
| ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
christospappas/streama | https://github.com/christospappas/streama/blob/2f6134437ba8f2364c12c0d836d4908be8a6b648/lib/streama/definition.rb | lib/streama/definition.rb | module Streama
class Definition
attr_reader :name, :actor, :object, :target_object, :receivers
# @param dsl [Streama::DefinitionDSL] A DSL object
def initialize(definition)
@name = definition[:name]
@actor = definition[:actor] || {}
@object = definition[:object] || {}
@target_object = definition[:target_object] || {}
end
#
# Registers a new definition
#
# @param definition [Definition] The definition to register
# @return [Definition] Returns the registered definition
def self.register(definition)
return false unless definition.is_a? DefinitionDSL
definition = new(definition)
self.registered << definition
return definition || false
end
# List of registered definitions
# @return [Array<Streama::Definition>]
def self.registered
@definitions ||= []
end
def self.find(name)
unless definition = registered.find{|definition| definition.name == name.to_sym}
raise Streama::Errors::InvalidActivity, "Could not find a definition for `#{name}`"
else
definition
end
end
end
end | ruby | MIT | 2f6134437ba8f2364c12c0d836d4908be8a6b648 | 2026-01-04T17:47:35.818726Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'grape/attack'
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/spec/grape/attack_spec.rb | spec/grape/attack_spec.rb | require 'spec_helper'
describe Grape::Attack do
it 'has a version number' do
expect(Grape::Attack::VERSION).not_to be nil
end
it 'does something useful' do
expect(false).to eq(true)
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack.rb | lib/grape/attack.rb | require 'active_support/core_ext/numeric/time.rb'
require 'grape'
require 'grape/attack/version'
require 'grape/attack/adapters/redis'
require 'grape/attack/adapters/memory'
require 'grape/attack/configurable'
require 'grape/attack/extension'
require 'grape/attack/exceptions'
require 'grape/attack/throttle'
module Grape
module Attack
extend Configurable
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/version.rb | lib/grape/attack/version.rb | module Grape
module Attack
VERSION = '0.3.0'
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/limiter.rb | lib/grape/attack/limiter.rb | require 'grape/attack/request'
require 'grape/attack/counter'
module Grape
module Attack
class Limiter
attr_reader :request, :adapter, :counter
def initialize(env, adapter = ::Grape::Attack.config.adapter)
@request = ::Grape::Attack::Request.new(env)
@adapter = adapter
@counter = ::Grape::Attack::Counter.new(@request, @adapter)
end
def call!
return if disable?
return unless throttle?
if allowed?
update_counter
set_rate_limit_headers
else
fail ::Grape::Attack::RateLimitExceededError.new("API rate limit exceeded for #{request.client_identifier}.")
end
end
private
def disable?
::Grape::Attack.config.disable.call
end
def throttle?
request.throttle?
end
def allowed?
counter.value < max_requests_allowed
end
def update_counter
counter.update
end
def set_rate_limit_headers
request.context.route_setting(:throttle)[:remaining] = [0, max_requests_allowed - (counter.value + 1)].max
end
def max_requests_allowed
request.throttle_options.max.to_i
end
end
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/exceptions.rb | lib/grape/attack/exceptions.rb | module Grape
module Attack
StoreError = Class.new(StandardError)
Exceptions = Class.new(StandardError)
RateLimitExceededError = Class.new(Exceptions)
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/options.rb | lib/grape/attack/options.rb | require 'active_model'
module Grape
module Attack
class Options
include ActiveModel::Model
include ActiveModel::Validations
attr_accessor :max, :per, :identifier, :remaining
class ProcOrNumberValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return true if value.is_a?(Numeric)
return true if value.is_a?(Proc) && value.call.is_a?(Numeric)
record.errors.add attribute, "must be either a proc resolving in a numeric or a numeric"
end
end
validates :max, proc_or_number: true
validates :per, proc_or_number: true
def identifier
@identifier || Proc.new {}
end
def max
return @max if @max.is_a?(Numeric)
return @max.call if @max.is_a?(Proc)
super
end
def per
return @per if @per.is_a?(Numeric)
return @per.call if @per.is_a?(Proc)
super
end
end
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/configuration.rb | lib/grape/attack/configuration.rb | module Grape
module Attack
class Configuration
attr_accessor :adapter, :disable
def initialize
@adapter = ::Grape::Attack::Adapters::Redis.new
@disable = Proc.new { false }
end
end
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/counter.rb | lib/grape/attack/counter.rb | module Grape
module Attack
class Counter
attr_reader :request, :adapter
def initialize(request, adapter)
@request = request
@adapter = adapter
end
def value
@value ||= begin
adapter.get(key).to_i
rescue ::Grape::Attack::StoreError
1
end
end
def update
adapter.atomically do
adapter.incr(key)
adapter.expire(key, ttl_in_seconds)
end
rescue ::Grape::Attack::StoreError
end
private
def key
"#{request.method}:#{request.path}:#{request.client_identifier}"
end
def ttl_in_seconds
request.throttle_options.per.to_i
end
end
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/request.rb | lib/grape/attack/request.rb | require 'grape/attack/options'
module Grape
module Attack
class Request
attr_reader :env, :context, :request, :throttle_options
def initialize(env)
@env = env
@context = env['api.endpoint']
@request = @context.routes.first
@throttle_options = ::Grape::Attack::Options.new(@context.route_setting(:throttle))
end
def method
request.request_method
end
def path
request.path
end
def params
request.params
end
def method_missing(method_name, *args, &block)
context.public_send(method_name, *args, &block)
end
def respond_to_missing?(method_name, include_private = false)
context.respond_to?(method_name)
end
def client_identifier
self.instance_eval(&throttle_options.identifier) || env['HTTP_X_REAL_IP'] || env['REMOTE_ADDR']
end
def throttle?
return false unless context.route_setting(:throttle).present?
return true if throttle_options.valid?
fail ArgumentError.new(throttle_options.errors.full_messages)
end
end
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/extension.rb | lib/grape/attack/extension.rb | module Grape
module Attack
module Extension
def throttle(options = {})
route_setting(:throttle, options)
options
end
::Grape::API.extend self
end
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/throttle.rb | lib/grape/attack/throttle.rb | require 'grape/attack/limiter'
module Grape
module Attack
class Throttle < Grape::Middleware::Base
def before
::Grape::Attack::Limiter.new(env).call!
end
def after
request = ::Grape::Attack::Request.new(env)
return if ::Grape::Attack.config.disable.call
return unless request.throttle?
header('X-RateLimit-Limit', request.throttle_options.max.to_s)
header('X-RateLimit-Reset', request.throttle_options.per.to_s)
header('X-RateLimit-Remaining', request.throttle_options.remaining.to_s)
@app_response
end
end
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/configurable.rb | lib/grape/attack/configurable.rb | require 'grape/attack/configuration'
module Grape
module Attack
module Configurable
def config
@config ||= ::Grape::Attack::Configuration.new
end
def configure
yield config if block_given?
end
end
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/adapters/memory.rb | lib/grape/attack/adapters/memory.rb | module Grape
module Attack
module Adapters
class Memory
attr_reader :data
def initialize
@data = {}
end
def get(key)
data[key]
end
def incr(key)
data[key] ||= 0
data[key] += 1
end
def expire(key, ttl_in_seconds)
end
def atomically(&block)
block.call
end
end
end
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
gottfrois/grape-attack | https://github.com/gottfrois/grape-attack/blob/cb7e6fddd13e9e4d4241521f96404abb7c628abf/lib/grape/attack/adapters/redis.rb | lib/grape/attack/adapters/redis.rb | require 'redis-namespace'
module Grape
module Attack
module Adapters
class Redis
attr_reader :broker
def initialize
@broker = ::Redis::Namespace.new("grape-attack:#{env}:thottle", redis: ::Redis.new(url: url))
end
def get(key)
with_custom_exception do
broker.get(key)
end
end
def incr(key)
with_custom_exception do
broker.incr(key)
end
end
def expire(key, ttl_in_seconds)
with_custom_exception do
broker.expire(key, ttl_in_seconds)
end
end
def atomically(&block)
broker.multi(&block)
end
private
def with_custom_exception(&block)
block.call
rescue ::Redis::BaseError => e
raise ::Grape::Attack::StoreError.new(e.message)
end
def env
if defined?(::Rails)
::Rails.env
elsif defined?(RACK_ENV)
RACK_ENV
else
ENV['RACK_ENV']
end
end
def url
ENV['REDIS_URL'] || 'redis://localhost:6379/0'
end
end
end
end
end
| ruby | MIT | cb7e6fddd13e9e4d4241521f96404abb7c628abf | 2026-01-04T17:47:37.008215Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/app/jobs/lets_encrypt/application_job.rb | app/jobs/lets_encrypt/application_job.rb | # frozen_string_literal: true
module LetsEncrypt
class ApplicationJob < ActiveJob::Base
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/app/jobs/lets_encrypt/renew_certificates_job.rb | app/jobs/lets_encrypt/renew_certificates_job.rb | # frozen_string_literal: true
module LetsEncrypt
# :nodoc:
class RenewCertificatesJob < ApplicationJob
queue_as :default
def perform
service = LetsEncrypt::RenewService.new
LetsEncrypt.certificate_model.renewable.each do |certificate|
service.execute(certificate)
rescue LetsEncrypt::MaxCheckExceeded, LetsEncrypt::InvalidStatus
certificate.update(renew_after: 1.day.from_now)
rescue Acme::Client::Error => e
certificate.update(renew_after: 1.day.from_now)
Rails.logger.error("LetsEncrypt::RenewCertificatesJob: #{e.message}")
end
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/app/controllers/lets_encrypt/verifications_controller.rb | app/controllers/lets_encrypt/verifications_controller.rb | # frozen_string_literal: true
require_dependency 'lets_encrypt/application_controller'
module LetsEncrypt
# :nodoc:
class VerificationsController < ApplicationController
def show
return render_verification_string if certificate.present?
render plain: 'Verification not found', status: :not_found
end
protected
def render_verification_string
render plain: certificate.verification_string
end
def certificate
LetsEncrypt.certificate_model.find_by(verification_path: filename)
end
def filename
".well-known/acme-challenge/#{params[:verification_path]}"
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/app/controllers/lets_encrypt/application_controller.rb | app/controllers/lets_encrypt/application_controller.rb | # frozen_string_literal: true
module LetsEncrypt
# :nodoc:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/app/models/lets_encrypt/certificate.rb | app/models/lets_encrypt/certificate.rb | # frozen_string_literal: true
module LetsEncrypt
# == Schema Information
#
# Table name: letsencrypt_certificates
#
# id :integer not null, primary key
# domain :string(255)
# certificate :text(65535)
# intermediaries :text(65535)
# key :text(65535)
# expires_at :datetime
# renew_after :datetime
# verification_path :string(255)
# verification_string :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_letsencrypt_certificates_on_domain (domain)
# index_letsencrypt_certificates_on_renew_after (renew_after)
#
class Certificate < ApplicationRecord
self.table_name = 'letsencrypt_certificates'
validates :domain, presence: true, uniqueness: true
scope :active, -> { where('certificate IS NOT NULL AND expires_at > ?', Time.zone.now) }
scope :renewable, -> { where('renew_after IS NULL OR renew_after <= ?', Time.zone.now) }
scope :expired, -> { where(expires_at: ..Time.zone.now) }
before_create -> { self.key = OpenSSL::PKey::RSA.new(4096).to_s }
after_destroy -> { delete_from_redis }, if: -> { LetsEncrypt.config.use_redis? && active? }
after_save -> { save_to_redis }, if: -> { LetsEncrypt.config.use_redis? && active? }
# Returns false if certificate is not issued.
#
# This method didn't check certificate is valid,
# its only uses for checking is there has a certificate.
def active?
certificate.present?
end
# Returns true if certificate is expired.
def expired?
Time.zone.now >= expires_at
end
# Returns full-chain bundled certificates
def bundle
(certificate || '') + (intermediaries || '')
end
def certificate_object
@certificate_object ||= OpenSSL::X509::Certificate.new(certificate)
end
def key_object
@key_object ||= OpenSSL::PKey::RSA.new(key)
end
def challenge!(filename, file_content)
update!(
verification_path: filename,
verification_string: file_content
)
end
def refresh!(cert, fullchain)
update!(
certificate: cert.to_pem,
intermediaries: fullchain.join("\n\n"),
expires_at: cert.not_after,
renew_after: (cert.not_after - 1.month) + rand(10).days
)
end
# Save certificate into redis
def save_to_redis
LetsEncrypt::Redis.save(self)
end
# Delete certificate from redis
def delete_from_redis
LetsEncrypt::Redis.delete(self)
end
# Returns true if success get a new certificate
def get
logger.info "Getting certificate for #{domain}"
service = LetsEncrypt::RenewService.new
service.execute(self)
logger.info "Certificate issued for #{domain} " \
"(expires on #{expires_at}, will renew after #{renew_after})"
true
rescue LetsEncrypt::MaxCheckExceeded, LetsEncrypt::InvalidStatus => e
logger.error "#{domain}: #{e.message}"
false
end
alias renew get
def verify
service = LetsEncrypt::VerifyService.new
service.execute(self, order)
true
rescue LetsEncrypt::MaxCheckExceeded, LetsEncrypt::InvalidStatus => e
logger.error "#{domain}: #{e.message}"
false
end
def issue
logger.info "Getting certificate for #{domain}"
service = LetsEncrypt::IssueService.new
service.execute(self, order)
logger.info "Certificate issued for #{domain} " \
"(expires on #{expires_at}, will renew after #{renew_after})"
true
rescue LetsEncrypt::MaxCheckExceeded, LetsEncrypt::InvalidStatus => e
logger.error "#{domain}: #{e.message}"
false
end
protected
def order
@order ||= LetsEncrypt.client.new_order(identifiers: [domain])
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/rails_helper.rb | spec/rails_helper.rb | # frozen_string_literal: true
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('dummy/config/environment', __dir__)
# Prevent database truncation if the environment is production
abort('The Rails environment is running in production mode!') if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[File.expand_path('../spec/support/**/*.rb', __dir__)].each { |f| require f }
ActiveRecord::Migrator.migrations_paths = [File.expand_path('../spec/dummy/db/migrate', __dir__)]
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = Rails.root.join('spec/fixtures').to_s
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
config.include AcmeTestHelper
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/letsencrypt_spec.rb | spec/letsencrypt_spec.rb | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe LetsEncrypt do
let(:tempfile) { Tempfile.new }
let(:key) { OpenSSL::PKey::RSA.new(2048) }
before do
LetsEncrypt.class_eval do
@private_key = nil
@endpoint = nil
end
LetsEncrypt.config.private_key_path = tempfile.path
end
describe '#generate_private_key' do
let!(:key) { LetsEncrypt.generate_private_key }
it { expect(LetsEncrypt.private_key.to_s).to eq(key.to_s) }
end
describe '#register' do
let(:acme_client) { double(Acme::Client) }
let(:acme_account) { double }
before do
tempfile.write(key.to_s)
tempfile.rewind
allow(LetsEncrypt).to receive(:client).and_return(acme_client)
allow(acme_client).to receive(:new_account).and_return(acme_account)
allow(acme_account).to receive(:kid).and_return('')
end
it { expect(LetsEncrypt.register('example@example.com')).to be_truthy }
end
describe 'certificate_model' do
before do
stub_const('OtherModel', Class.new(LetsEncrypt::Certificate))
LetsEncrypt.config.certificate_model = 'OtherModel'
allow(LetsEncrypt).to receive(:certificate_model) { LetsEncrypt.config.certificate_model.constantize }
end
after { LetsEncrypt.config.certificate_model = 'LetsEncrypt::Certificate' }
it { expect(LetsEncrypt).to have_attributes(certificate_model: OtherModel) }
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'simplecov'
require 'webmock/rspec'
SimpleCov.start do
formatter SimpleCov::Formatter::MultiFormatter.new(
[
SimpleCov::Formatter::HTMLFormatter
]
)
load_profile 'test_frameworks'
add_group 'Let\'s Encrypt', 'lib/letsencrypt'
add_group 'Generators', 'lib/generators/lets_encrypt'
add_group 'Controllers', 'app/controllers'
add_group 'Models', 'app/models'
add_group 'Jobs', 'app/jobs'
add_filter '/generators\/(.+)\/templates/'
track_files '{app,lib}/**/*.rb'
end
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => 'be bigger than 2 and smaller than 4'
# ...rather than:
# # => 'be bigger than 2'
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
# # This allows you to limit a spec run to individual examples or groups
# # you care about by tagging them with `:focus` metadata. When nothing
# # is tagged with `:focus`, all examples get run. RSpec also provides
# # aliases for `it`, `describe`, and `context` that include `:focus`
# # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
# config.filter_run_when_matching :focus
#
# # Allows RSpec to persist some state between runs in order to support
# # the `--only-failures` and `--next-failure` CLI options. We recommend
# # you configure your source control system to ignore this file.
# config.example_status_persistence_file_path = 'spec/examples.txt'
#
# # Limits the available syntax to the non-monkey patched syntax that is
# # recommended. For more details, see:
# # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
# config.disable_monkey_patching!
#
# # Many RSpec users commonly either run the entire suite or an individual
# # file, and it's useful to allow more verbose output when running an
# # individual spec file.
# if config.files_to_run.one?
# # Use the documentation formatter for detailed output,
# # unless a formatter has already been configured
# # (e.g. via a command-line flag).
# config.default_formatter = 'doc'
# end
#
# # Print the 10 slowest examples and example groups at the
# # end of the spec run, to help surface which specs are running
# # particularly slow.
# config.profile_examples = 10
#
# # Run specs in random order to surface order dependencies. If you find an
# # order dependency and want to debug it, you can fix the order by providing
# # the seed, which is printed after each run.
# # --seed 1234
# config.order = :random
#
# # Seed global randomization in this process using the `--seed` CLI option.
# # Setting this allows you to use `--seed` to deterministically reproduce
# # test failures related to randomization by passing the same `--seed` value
# # as the one that triggered the failure.
# Kernel.srand config.seed
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/jobs/lets_encrypt/renew_certificates_job_spec.rb | spec/jobs/lets_encrypt/renew_certificates_job_spec.rb | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe LetsEncrypt::RenewCertificatesJob, type: :job do
subject(:renew) { LetsEncrypt::RenewCertificatesJob.perform_now }
let(:certificate) { LetsEncrypt::Certificate.create!(domain: 'example.com') }
let(:pem) do
<<~PEM
-----BEGIN CERTIFICATE-----
MIICjzCCAXcCAQAwDQYJKoZIhvcNAQELBQAwADAeFw0yNTA1MTgwODMyMDRaFw0y
NTA2MTcwODMyMTNaMBsxGTAXBgNVBAMMEGV4YW1wbGUuY29tL0M9RUUwggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqOFgqYlK8OUfmcL1zLOAWOY69zPQS
Cst+bXUjL/Lf7pz25bFraQZ7sbFgkEqsJ4N6VmdkeSYABCfSaGMsD3WygCeONdek
Z7r0GPJ/nN9GGoJt576PqSc5nIj3odYfIWY0Rg5ZxAzYkbZL4PBfX2nzR0DHmuiB
4xAawCy/1gUZcdJdVuLKcm88c7ptZuvDWtk3k++tawsayz+Su6pyZb7Ib9Bnt4Jx
ZZBJwRqYQF7L+PCmXydR+Te7XI0KjaIonqnvOh4lEq8HH41QZz8ptqYK2wZgRrB9
3AZAYv9FS+qWx5Sdn98OhX68lJwYXCx195jDfJZyNS6G4m+bsJGtNxLrAgMBAAEw
DQYJKoZIhvcNAQELBQADggEBAFlDgb8vDPaCvmA2sRY3QvmJZh8jPFX1nANmNrWr
ZgMFXP2EmrPqpgW7k3LlZ3pcYg5CruRH4+oTnCeHfryda1Ko8z8MS9Zslrz7CmaW
7GExw2jH3Ns4OXAwak03uiW9vRxGxcfRoqluFH/yO6lx6a8Hy4ZS++BlWju3SwJ1
kD/e8Tv917jhm9BJZvLkLOwwXI3CWSVZdctwVl7PtNrMaFlZaMqa7SwbF2lbjuZQ
Svg/K5bzrZmhA6YDFLQs4HOcshK0pmpoj4TtLlulgnVv2BLjXDlpGdbK5KtXc4qg
+vsUzgp55BU0Um2XKQPL+VtR9s58lrX2UiUKD3+nWzp0Fpg=
-----END CERTIFICATE-----
PEM
end
before do
ActiveJob::Base.queue_adapter = :test
LetsEncrypt.config do |config|
config.retry_interval = 0
end
given_acme_directory
given_acme_account
given_acme_nonce
given_acme_order
given_acme_authorization
given_acme_finalize(status: 'ready')
given_acme_certificate(pem:)
allow(LetsEncrypt::Certificate).to receive(:renewable).and_return([certificate])
end
describe 'when renew success' do
before do
given_acme_challenge(status: 'valid')
end
it {
expect { renew }.to change(certificate, :expires_at).to(satisfy do |time|
time >= Time.zone.parse('2025-06-17T00:00')
end)
}
end
describe 'renew failed' do
before do
given_acme_challenge(status: %w[pending invalid])
end
it { expect { renew }.not_to change(certificate, :expires_at) }
it { expect { renew }.to change(certificate, :renew_after).from(nil) }
end
describe 'when Acme::Client::Error' do
let(:service) { spy(LetsEncrypt::RenewService) }
before do
allow(LetsEncrypt::RenewService).to receive(:new).and_return(service)
allow(service).to receive(:execute).and_raise(Acme::Client::Error.new('Unexpected error'))
end
it { expect { renew }.not_to change(certificate, :expires_at) }
it { expect { renew }.to change(certificate, :renew_after).from(nil) }
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/support/acme.rb | spec/support/acme.rb | # frozen_string_literal: true
module AcmeTestHelper # rubocop:disable Metrics/ModuleLength
# This module contains helper methods to stub ACME requests
# in the tests. It uses WebMock to intercept HTTP requests
# and return predefined responses.
DIRECTORY_BODY = <<~JSON
{
"keyChange": "https://acme-staging-v02.api.letsencrypt.org/acme/key-change",
"meta": {
"caaIdentities": [
"letsencrypt.org"
],
"profiles": {
"classic": "https://letsencrypt.org/docs/profiles#classic",
"shortlived": "https://letsencrypt.org/docs/profiles#shortlived (not yet generally available)",
"tlsserver": "https://letsencrypt.org/docs/profiles#tlsserver"
},
"termsOfService": "https://letsencrypt.org/documents/LE-SA-v1.5-February-24-2025.pdf",
"website": "https://letsencrypt.org/docs/staging-environment/"
},
"newAccount": "https://acme-staging-v02.api.letsencrypt.org/acme/new-acct",
"newNonce": "https://acme-staging-v02.api.letsencrypt.org/acme/new-nonce",
"newOrder": "https://acme-staging-v02.api.letsencrypt.org/acme/new-order",
"renewalInfo": "https://acme-staging-v02.api.letsencrypt.org/draft-ietf-acme-ari-03/renewalInfo",
"revokeCert": "https://acme-staging-v02.api.letsencrypt.org/acme/revoke-cert"
}
JSON
ORDER_BODY = <<~JSON
{
"status": "%<status>s",
"expires": "2016-01-05T14:09:07.99Z",
"notBefore": "2016-01-01T00:00:00Z",
"notAfter": "2016-01-08T00:00:00Z",
"identifiers": [
{ "type": "dns", "value": "%<domain>s" }
],
"authorizations": [
"https://acme-staging-v02.api.letsencrypt.org/acme/authz/r4HqLzrSrpI"
],
"finalize": "https://acme-staging-v02.api.letsencrypt.org/acme/order/TOlocE8rfgo/finalize"
}
JSON
AUTHZ_BODY = <<~JSON
{
"status": "%<status>s",
"expires": "2016-01-02T14:09:30Z",
"identifier": {
"type": "dns",
"value": "%<domain>s"
},
"challenges": [
{
"type": "http-01",
"status": "pending",
"url": "https://acme-staging-v02.api.letsencrypt.org/acme/chall/prV_B7yEyA4",
"token": "DGyRejmCefe7v4NfDGDKfA"
},
{
"type": "dns-01",
"status": "pending",
"url": "https://acme-staging-v02.api.letsencrypt.org/acme/chall/Rg5dV14Gh1Q",
"token": "DGyRejmCefe7v4NfDGDKfA"
}
]
}
JSON
CHALLENGE_BODY = <<~JSON
{
"type": "http-01",
"status": "%<status>s",
"url": "https://acme-staging-v02.api.letsencrypt.org/acme/chall/prV_B7yEyA4",
"token": "DGyRejmCefe7v4NfDGDKfA"
}
JSON
ORDER_FINALIZE_BODY = <<~JSON
{
"status": "%<status>s",
"expires": "2016-01-20T14:09:07.99Z",
"notBefore": "2016-01-01T00:00:00Z",
"notAfter": "2016-01-08T00:00:00Z",
"identifiers": [
{ "type": "dns", "value": "%<domain>s" }
],
"authorizations": [
"https://acme-staging-v02.api.letsencrypt.org/acme/authz/r4HqLzrSrpI"
],
"finalize": "https://acme-staging-v02.api.letsencrypt.org/acme/order/TOlocE8rfgo/finalize",
"certificate": "https://acme-staging-v02.api.letsencrypt.org/acme/cert/mAt3xBGaobw"
}
JSON
def given_acme_directory
stub_request(:get, 'https://acme-staging-v02.api.letsencrypt.org/directory')
.to_return(status: 200, body: DIRECTORY_BODY, headers: {
'Content-Type' => 'application/json'
})
end
def given_acme_nonce(nonce: 'dummy-nonce')
stub_request(:head, 'https://acme-staging-v02.api.letsencrypt.org/acme/new-nonce')
.to_return(status: 204, body: '', headers: {
'Replay-Nonce' => nonce
})
end
def given_acme_account
stub_request(:post, 'https://acme-staging-v02.api.letsencrypt.org/acme/new-acct')
.to_return(status: 200, body: '{}', headers: {
'Content-Type' => 'application/json',
'Location' => 'https://acme-staging-v02.api.letsencrypt.org/acme/acct/evOfKhNU60wg'
})
stub_request(:post, 'https://acme-staging-v02.api.letsencrypt.org/acme/acct/evOfKhNU60wg')
.to_return(status: 200, body: '{}', headers: {
'Content-Type' => 'application/json'
})
end
def given_acme_order(status: 'valid', domain: 'example.com') # rubocop:disable Metrics/MethodLength
responses = Array.wrap(status).map do |s|
{
status: 200, body: format(ORDER_FINALIZE_BODY, status: s, domain:),
headers: {
'Location' => 'https://acme-staging-v02.api.letsencrypt.org/acme/order/TOlocE8rfgo',
'Content-Type' => 'application/json'
}
}
end
stub_request(:post, 'https://acme-staging-v02.api.letsencrypt.org/acme/new-order')
.to_return(status: 200, body: format(ORDER_BODY, status: 'pending', domain:), headers: {
'Location' => 'https://acme-staging-v02.api.letsencrypt.org/acme/order/TOlocE8rfgo',
'Content-Type' => 'application/json'
})
stub_request(:post, 'https://acme-staging-v02.api.letsencrypt.org/acme/order/TOlocE8rfgo')
.to_return(*responses)
end
def given_acme_authorization(status: 'pending', domain: 'example.com')
responses = Array.wrap(status).map do |s|
{
status: 200, body: format(AUTHZ_BODY, status: s, domain:),
headers: {
'Content-Type' => 'application/json'
}
}
end
stub_request(:post, 'https://acme-staging-v02.api.letsencrypt.org/acme/authz/r4HqLzrSrpI')
.to_return(*responses)
end
def given_acme_challenge(status: 'pending')
responses = Array.wrap(status).map do |s|
{
status: 200, body: format(CHALLENGE_BODY, status: s),
headers: {
'Content-Type' => 'application/json'
}
}
end
stub_request(:post, 'https://acme-staging-v02.api.letsencrypt.org/acme/chall/prV_B7yEyA4')
.to_return(*responses)
end
def given_acme_finalize(status: 'procesing', domain: 'example.com') # rubocop:disable Metrics/MethodLength
responses = Array.wrap(status).map do |s|
{
status: 200, body: format(ORDER_FINALIZE_BODY, status: s, domain:),
headers: {
'Location' => 'https://acme-staging-v02.api.letsencrypt.org/acme/order/TOlocE8rfgo',
'Content-Type' => 'application/json'
}
}
end
stub_request(:post, 'https://acme-staging-v02.api.letsencrypt.org/acme/order/TOlocE8rfgo/finalize')
.to_return(*responses)
end
def given_acme_certificate(pem:)
stub_request(:post, 'https://acme-staging-v02.api.letsencrypt.org/acme/cert/mAt3xBGaobw')
.to_return(status: 200, body: pem, headers: {
'Content-Type' => 'application/pem-certificate-chain'
})
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/controllers/lets_encrypt/verifications_controller_spec.rb | spec/controllers/lets_encrypt/verifications_controller_spec.rb | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe LetsEncrypt::VerificationsController, type: :controller do
routes { LetsEncrypt::Engine.routes }
subject { get :show, params: { verification_path: } }
let(:verification_path) { :invalid_path }
describe 'with invalid path' do
it { is_expected.to be_not_found }
end
describe 'with default model' do
let!(:certificate) do
LetsEncrypt.certificate_model.create(
domain: 'example.com',
verification_path: '.well-known/acme-challenge/valid_path',
verification_string: 'verification'
)
end
let(:verification_path) { 'valid_path' }
it { is_expected.to be_ok }
it { is_expected.to have_attributes(body: certificate.verification_string) }
end
describe 'with customize model' do
let!(:certificate) do
LetsEncrypt.certificate_model.create(
domain: 'example.com',
verification_path: '.well-known/acme-challenge/valid_path',
verification_string: 'verification'
)
end
let(:verification_path) { 'valid_path' }
before { LetsEncrypt.config.certificate_model = 'OtherModel' }
after { LetsEncrypt.config.certificate_model = 'LetsEncrypt::Certificate' }
it { is_expected.to be_ok }
it { is_expected.to have_attributes(body: certificate.verification_string) }
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/models/lets_encrypt/certificate_spec.rb | spec/models/lets_encrypt/certificate_spec.rb | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe LetsEncrypt::Certificate do
subject(:cert) { LetsEncrypt::Certificate.new(domain: 'example.com') }
let(:key) { OpenSSL::PKey::RSA.new(4096) }
let(:pem) do
<<~PEM
-----BEGIN CERTIFICATE-----
MIICjzCCAXcCAQAwDQYJKoZIhvcNAQELBQAwADAeFw0yNTA1MTgwODMyMDRaFw0y
NTA2MTcwODMyMTNaMBsxGTAXBgNVBAMMEGV4YW1wbGUuY29tL0M9RUUwggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqOFgqYlK8OUfmcL1zLOAWOY69zPQS
Cst+bXUjL/Lf7pz25bFraQZ7sbFgkEqsJ4N6VmdkeSYABCfSaGMsD3WygCeONdek
Z7r0GPJ/nN9GGoJt576PqSc5nIj3odYfIWY0Rg5ZxAzYkbZL4PBfX2nzR0DHmuiB
4xAawCy/1gUZcdJdVuLKcm88c7ptZuvDWtk3k++tawsayz+Su6pyZb7Ib9Bnt4Jx
ZZBJwRqYQF7L+PCmXydR+Te7XI0KjaIonqnvOh4lEq8HH41QZz8ptqYK2wZgRrB9
3AZAYv9FS+qWx5Sdn98OhX68lJwYXCx195jDfJZyNS6G4m+bsJGtNxLrAgMBAAEw
DQYJKoZIhvcNAQELBQADggEBAFlDgb8vDPaCvmA2sRY3QvmJZh8jPFX1nANmNrWr
ZgMFXP2EmrPqpgW7k3LlZ3pcYg5CruRH4+oTnCeHfryda1Ko8z8MS9Zslrz7CmaW
7GExw2jH3Ns4OXAwak03uiW9vRxGxcfRoqluFH/yO6lx6a8Hy4ZS++BlWju3SwJ1
kD/e8Tv917jhm9BJZvLkLOwwXI3CWSVZdctwVl7PtNrMaFlZaMqa7SwbF2lbjuZQ
Svg/K5bzrZmhA6YDFLQs4HOcshK0pmpoj4TtLlulgnVv2BLjXDlpGdbK5KtXc4qg
+vsUzgp55BU0Um2XKQPL+VtR9s58lrX2UiUKD3+nWzp0Fpg=
-----END CERTIFICATE-----
PEM
end
before do
LetsEncrypt.config do |config|
config.retry_interval = 0
config.save_to_redis = false
end
given_acme_directory
given_acme_account
given_acme_nonce
given_acme_order
given_acme_authorization
given_acme_challenge(status: 'valid')
given_acme_finalize
given_acme_certificate(pem:)
end
describe '#active?' do
before { cert.certificate = pem }
it { is_expected.to be_active }
end
describe '#exipred?' do
before { cert.expires_at = 3.days.ago }
it { is_expected.to be_expired }
end
describe '#get' do
subject { cert.get }
it { is_expected.to be_truthy }
end
describe '#save_to_redis' do
subject(:cert) { LetsEncrypt::Certificate.new(domain: 'example.com') }
before do
allow(LetsEncrypt::Redis).to receive(:save)
LetsEncrypt.config.save_to_redis = true
cert.save
end
it { expect(LetsEncrypt::Redis).not_to have_received(:save) }
describe 'when certificate is present' do
subject(:cert) do
LetsEncrypt::Certificate.new(
domain: 'example.com',
certificate: pem,
key:
)
end
it { expect(LetsEncrypt::Redis).to have_received(:save) }
end
end
describe '#delete_from_redis' do
subject(:cert) { LetsEncrypt::Certificate.new(domain: 'example.com') }
before do
allow(LetsEncrypt::Redis).to receive(:delete)
LetsEncrypt.config.save_to_redis = true
cert.destroy
end
it { expect(LetsEncrypt::Redis).not_to have_received(:delete) }
describe 'when certificate is present' do
subject(:cert) do
LetsEncrypt::Certificate.new(
domain: 'example.com',
certificate: pem,
key:
)
end
it { expect(LetsEncrypt::Redis).to have_received(:delete) }
end
end
describe '#verify' do
subject(:cert) { LetsEncrypt::Certificate.new(domain: 'example.com') }
describe 'when status is valid' do
it { is_expected.to have_attributes(verify: true) }
end
describe 'when status is pending to valid' do
before do
given_acme_challenge(status: %w[pending valid])
end
it { is_expected.to have_attributes(verify: true) }
end
end
describe '#issue' do
subject(:cert) { LetsEncrypt::Certificate.new(domain: 'example.com', key:) }
it { is_expected.to have_attributes(issue: true) }
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/app/jobs/application_job.rb | spec/dummy/app/jobs/application_job.rb | class ApplicationJob < ActiveJob::Base
# Automatically retry jobs that encountered a deadlock
# retry_on ActiveRecord::Deadlocked
# Most jobs are safe to ignore if the underlying records are no longer available
# discard_on ActiveJob::DeserializationError
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/app/helpers/application_helper.rb | spec/dummy/app/helpers/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/app/controllers/application_controller.rb | spec/dummy/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/app/models/application_record.rb | spec/dummy/app/models/application_record.rb | class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/app/mailers/application_mailer.rb | spec/dummy/app/mailers/application_mailer.rb | class ApplicationMailer < ActionMailer::Base
default from: 'from@example.com'
layout 'mailer'
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/db/schema.rb | spec/dummy/db/schema.rb | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_02_11_034819) do
create_table "letsencrypt_certificates", force: :cascade do |t|
t.string "domain"
t.text "certificate", limit: 65535
t.text "intermediaries", limit: 65535
t.text "key", limit: 65535
t.datetime "expires_at"
t.datetime "renew_after"
t.string "verification_path"
t.string "verification_string"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["domain"], name: "index_letsencrypt_certificates_on_domain"
t.index ["renew_after"], name: "index_letsencrypt_certificates_on_renew_after"
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/db/migrate/20200211034819_create_letsencrypt_certificates.rb | spec/dummy/db/migrate/20200211034819_create_letsencrypt_certificates.rb | # frozen_string_literal: true
# :nodoc:
class CreateLetsencryptCertificates < ActiveRecord::Migration[5.2]
def change
create_table :letsencrypt_certificates do |t|
t.string :domain
t.text :certificate, limit: 65535
t.text :intermediaries, limit: 65535
t.text :key, limit: 65535
t.datetime :expires_at
t.datetime :renew_after
t.string :verification_path
t.string :verification_string
t.index :domain
t.index :renew_after
t.timestamps
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/application.rb | spec/dummy/config/application.rb | # frozen_string_literal: true
require 'rails/version'
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
require 'rails-letsencrypt'
module Dummy
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
case Rails::VERSION::MAJOR
when 8
config.load_defaults 8.0
when 7
config.load_defaults 7.2
end
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/environment.rb | spec/dummy/config/environment.rb | # Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/puma.rb | spec/dummy/config/puma.rb | # Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers: a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
threads min_threads_count, max_threads_count
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3000 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the `pidfile` that Puma will use.
pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked web server processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory.
#
# preload_app!
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/routes.rb | spec/dummy/config/routes.rb | Rails.application.routes.draw do
mount LetsEncrypt::Engine => '/.well-known'
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/spring.rb | spec/dummy/config/spring.rb | Spring.watch(
".ruby-version",
".rbenv-vars",
"tmp/restart.txt",
"tmp/caching-dev.txt"
)
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/boot.rb | spec/dummy/config/boot.rb | # Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
$LOAD_PATH.unshift File.expand_path('../../../lib', __dir__)
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/initializers/content_security_policy.rb | spec/dummy/config/initializers/content_security_policy.rb | # Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
# Rails.application.config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end
# If you are using UJS then enable automatic nonce generation
# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Set the nonce only to specific directives
# Rails.application.config.content_security_policy_nonce_directives = %w(script-src)
# Report CSP violations to a specified URI
# For further information see the following documentation:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# Rails.application.config.content_security_policy_report_only = true
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/initializers/filter_parameter_logging.rb | spec/dummy/config/initializers/filter_parameter_logging.rb | # Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/initializers/application_controller_renderer.rb | spec/dummy/config/initializers/application_controller_renderer.rb | # Be sure to restart your server when you modify this file.
# ActiveSupport::Reloader.to_prepare do
# ApplicationController.renderer.defaults.merge!(
# http_host: 'example.org',
# https: false
# )
# end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/initializers/wrap_parameters.rb | spec/dummy/config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/initializers/inflections.rb | spec/dummy/config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/initializers/cookies_serializer.rb | spec/dummy/config/initializers/cookies_serializer.rb | # Be sure to restart your server when you modify this file.
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :json
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/initializers/backtrace_silencers.rb | spec/dummy/config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/initializers/mime_types.rb | spec/dummy/config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/environments/test.rb | spec/dummy/config/environments/test.rb | # The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
config.cache_classes = false
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{1.hour.to_i}"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.cache_store = :null_store
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/environments/development.rb | spec/dummy/config/environments/development.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
# config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/dummy/config/environments/production.rb | spec/dummy/config/environments/production.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "dummy_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/letsencrypt/redis_spec.rb | spec/letsencrypt/redis_spec.rb | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe LetsEncrypt::Redis do
let(:redis) { double(Redis) }
let(:domain) { 'example.com' }
let(:certificate) do
LetsEncrypt::Certificate.new(domain:, key: 'KEY', certificate: 'CERTIFICATE')
end
before(:each) do
allow(Redis).to receive(:new).and_return(redis)
end
after do
# Reset connection because redis double will work only for single example
LetsEncrypt::Redis.instance_variable_set('@connection', nil)
end
describe '#save' do
before do
allow(redis).to receive(:set).with("#{domain}.key", an_instance_of(String))
allow(redis).to receive(:set).with("#{domain}.crt", an_instance_of(String))
LetsEncrypt::Redis.save(certificate)
end
it { expect(redis).to have_received(:set).with("#{domain}.key", 'KEY') }
it { expect(redis).to have_received(:set).with("#{domain}.crt", 'CERTIFICATE') }
describe 'when key and certificate is empty' do
let(:certificate) do
LetsEncrypt::Certificate.new(domain:, key: '', certificate: '')
end
it { expect(redis).not_to have_received(:set).with("#{domain}.key", an_instance_of(String)) }
it { expect(redis).not_to have_received(:set).with("#{domain}.crt", an_instance_of(String)) }
end
end
describe '#delete' do
before do
allow(redis).to receive(:del).with("#{domain}.key")
allow(redis).to receive(:del).with("#{domain}.crt")
LetsEncrypt::Redis.delete(certificate)
end
it { expect(redis).to have_received(:del).with("#{domain}.key") }
it { expect(redis).to have_received(:del).with("#{domain}.crt") }
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/letsencrypt/configuration_spec.rb | spec/letsencrypt/configuration_spec.rb | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe LetsEncrypt::Configuration do
subject(:config) { LetsEncrypt::Configuration.new }
describe '#use_redis?' do
before { config.save_to_redis = true }
it { is_expected.to be_use_redis }
end
describe '#use_staging?' do
before { config.use_staging = true }
it { is_expected.to be_use_staging }
end
describe 'customize certificate model' do
before(:each) { config.certificate_model = 'OtherModel' }
after { LetsEncrypt.config.certificate_model = 'LetsEncrypt::Certificate' }
it { is_expected.to have_attributes(certificate_model: 'OtherModel') }
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/letsencrypt/renew_service_spec.rb | spec/letsencrypt/renew_service_spec.rb | # frozen_string_literal: true
RSpec.describe LetsEncrypt::RenewService do
subject(:renew) { service.execute(certificate) }
let(:service) { described_class.new }
let(:certificate) { LetsEncrypt::Certificate.create!(domain: 'example.com') }
let(:pem) do
<<~PEM
-----BEGIN CERTIFICATE-----
MIICjzCCAXcCAQAwDQYJKoZIhvcNAQELBQAwADAeFw0yNTA1MTgwODMyMDRaFw0y
NTA2MTcwODMyMTNaMBsxGTAXBgNVBAMMEGV4YW1wbGUuY29tL0M9RUUwggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqOFgqYlK8OUfmcL1zLOAWOY69zPQS
Cst+bXUjL/Lf7pz25bFraQZ7sbFgkEqsJ4N6VmdkeSYABCfSaGMsD3WygCeONdek
Z7r0GPJ/nN9GGoJt576PqSc5nIj3odYfIWY0Rg5ZxAzYkbZL4PBfX2nzR0DHmuiB
4xAawCy/1gUZcdJdVuLKcm88c7ptZuvDWtk3k++tawsayz+Su6pyZb7Ib9Bnt4Jx
ZZBJwRqYQF7L+PCmXydR+Te7XI0KjaIonqnvOh4lEq8HH41QZz8ptqYK2wZgRrB9
3AZAYv9FS+qWx5Sdn98OhX68lJwYXCx195jDfJZyNS6G4m+bsJGtNxLrAgMBAAEw
DQYJKoZIhvcNAQELBQADggEBAFlDgb8vDPaCvmA2sRY3QvmJZh8jPFX1nANmNrWr
ZgMFXP2EmrPqpgW7k3LlZ3pcYg5CruRH4+oTnCeHfryda1Ko8z8MS9Zslrz7CmaW
7GExw2jH3Ns4OXAwak03uiW9vRxGxcfRoqluFH/yO6lx6a8Hy4ZS++BlWju3SwJ1
kD/e8Tv917jhm9BJZvLkLOwwXI3CWSVZdctwVl7PtNrMaFlZaMqa7SwbF2lbjuZQ
Svg/K5bzrZmhA6YDFLQs4HOcshK0pmpoj4TtLlulgnVv2BLjXDlpGdbK5KtXc4qg
+vsUzgp55BU0Um2XKQPL+VtR9s58lrX2UiUKD3+nWzp0Fpg=
-----END CERTIFICATE-----
PEM
end
let(:output) { StringIO.new }
before do
LetsEncrypt.config do |config|
config.retry_interval = 0
end
given_acme_directory
given_acme_account
given_acme_nonce
given_acme_order
given_acme_authorization
given_acme_challenge(status: 'valid')
given_acme_finalize(status: 'ready')
given_acme_certificate(pem:)
end
context 'when renew subscribed' do
before do
ActiveSupport::Notifications.subscribe('letsencrypt.renew') do |_, _, _, _, payload|
output.puts "#{payload[:domain]} is renewed"
end
end
it { expect { renew }.to change(output, :string).to include('example.com is renewed') }
end
context 'when verify subscribed' do
before do
ActiveSupport::Notifications.subscribe('letsencrypt.verify') do |_, _, _, _, payload|
output.puts "#{payload[:domain]} is verified"
end
end
it { expect { renew }.to change(output, :string).to include('example.com is verified') }
end
context 'when issue subscribed' do
before do
ActiveSupport::Notifications.subscribe('letsencrypt.issue') do |_, _, _, _, payload|
output.puts "#{payload[:domain]} is issued"
end
end
it { expect { renew }.to change(output, :string).to include('example.com is issued') }
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/letsencrypt/generators/lets_encrypt/register_generator_spec.rb | spec/letsencrypt/generators/lets_encrypt/register_generator_spec.rb | # frozen_string_literal: true
require 'rails_helper'
require 'rails/generators/test_case'
require 'generators/lets_encrypt/register_generator'
RSpec.describe LetsEncrypt::Generators::RegisterGenerator do
let(:klass) do
Class.new(Rails::Generators::TestCase) do
tests LetsEncrypt::Generators::RegisterGenerator
destination Rails.root.join('tmp')
end
end
let(:generator) { klass.new(:fake_test_case) }
before do
answers = [
'', # In production
'', # File path
'Y', # Overwrite?
'example@example.com' # E-Mail
]
allow(Thor::LineEditor).to receive(:readline) { answers.shift.dup || 'N' }
allow(LetsEncrypt).to receive(:register).and_return(true)
generator.send(:prepare_destination)
generator.run_generator
end
it { expect(LetsEncrypt).to have_received(:register).with('example@example.com') }
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/spec/letsencrypt/generators/lets_encrypt/install_generator_spec.rb | spec/letsencrypt/generators/lets_encrypt/install_generator_spec.rb | # frozen_string_literal: true
require 'rails_helper'
require 'rails/generators/test_case'
require 'generators/lets_encrypt/install_generator'
RSpec.describe LetsEncrypt::Generators::InstallGenerator do
let(:klass) do
Class.new(Rails::Generators::TestCase) do
tests LetsEncrypt::Generators::InstallGenerator
destination Rails.root.join('tmp')
end
end
let(:generator) { klass.new(:fake_test_case) }
before do
generator.send(:prepare_destination)
generator.run_generator
end
it do
generator.assert_migration 'db/migrate/create_letsencrypt_certificates.rb', /def change/
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/rails-letsencrypt.rb | lib/rails-letsencrypt.rb | # frozen_string_literal: true
require 'letsencrypt'
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/letsencrypt.rb | lib/letsencrypt.rb | # frozen_string_literal: true
require 'openssl'
require 'acme-client'
require 'redis'
require 'letsencrypt/railtie'
require 'letsencrypt/engine'
require 'letsencrypt/errors'
require 'letsencrypt/configuration'
require 'letsencrypt/redis'
require 'letsencrypt/status_checker'
require 'letsencrypt/verify_service'
require 'letsencrypt/issue_service'
require 'letsencrypt/renew_service'
# :nodoc:
module LetsEncrypt
# Production mode API Endpoint
ENDPOINT = 'https://acme-v02.api.letsencrypt.org/directory'
# Staging mode API Endpoint, the rate limit is higher
# but got invalid certificate for testing
ENDPOINT_STAGING = 'https://acme-staging-v02.api.letsencrypt.org/directory'
class << self
# Create the ACME Client to Let's Encrypt
def client
@client ||= ::Acme::Client.new(
private_key:,
directory:,
bad_nonce_retry: 5
)
end
def private_key
@private_key ||= OpenSSL::PKey::RSA.new(load_private_key)
end
def load_private_key
return ENV.fetch('LETSENCRYPT_PRIVATE_KEY', nil) if config.use_env_key
return File.open(private_key_path) if File.exist?(private_key_path)
generate_private_key
end
# Get current using Let's Encrypt endpoint
def directory
@directory ||= config.acme_directory ||
(config.use_staging? ? ENDPOINT_STAGING : ENDPOINT)
end
# Register a Let's Encrypt account
#
# This is required a private key to do this,
# and Let's Encrypt will use this private key to
# connect with domain and assign the owner who can
# renew and revoked.
def register(email)
account = client.new_account(contact: "mailto:#{email}", terms_of_service_agreed: true)
logger.info "Successfully registered private key with address #{email}"
account.kid # TODO: Save KID
true
end
def private_key_path
config.private_key_path || Rails.root.join('config/letsencrypt.key')
end
def generate_private_key
key = OpenSSL::PKey::RSA.new(4096)
File.write(private_key_path, key.to_s)
logger.info "Created new private key for Let's Encrypt"
key
end
def logger
@logger ||= Rails.logger.tagged('LetsEncrypt')
end
# Config how to Let's Encrypt works for Rails
#
# LetsEncrypt.config do |config|
# # Always use production mode to connect Let's Encrypt API server
# config.use_staging = false
# end
def config(&)
@config ||= Configuration.new
instance_exec(@config, &) if block_given?
@config
end
def certificate_model
@certificate_model ||= config.certificate_model.constantize
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/generators/lets_encrypt/register_generator.rb | lib/generators/lets_encrypt/register_generator.rb | # frozen_string_literal: true
require 'rails/generators'
require 'rails/generators/migration'
require 'rails/generators/active_record'
module LetsEncrypt
module Generators
# :nodoc:
class RegisterGenerator < ::Rails::Generators::Base
def register
say 'Starting register Let\'s Encrypt account', :green
setup_environment
generate_key
register_email
rescue Acme::Client::Error => e
say(e.message, :red)
end
private
def setup_environment
production = yes?('Do you want to use in production environment? [y/N]:')
LetsEncrypt.config.use_staging = !production
end
def generate_key
key_path = ask("Where you to save private key [#{LetsEncrypt.private_key_path}]:", path: true)
key_path = LetsEncrypt.private_key_path if key_path.blank?
return unless file_collision(key_path)
FileUtils.rm_f(key_path)
LetsEncrypt.config.use_env_key = false
LetsEncrypt.config.private_key_path = key_path
LetsEncrypt.load_private_key
say "Your privated key is saved in #{key_path}, make sure setup configure for your rails.", :yellow
end
def register_email
email = ask('What email you want to register:')
return say('Email is inavlid!', :red) if email.blank?
LetsEncrypt.register(email)
say 'Register successed, don\'t forget backup your private key', :green
end
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/generators/lets_encrypt/install_generator.rb | lib/generators/lets_encrypt/install_generator.rb | # frozen_string_literal: true
require 'rails/generators'
require 'rails/generators/migration'
require 'rails/generators/active_record'
module LetsEncrypt
module Generators
# :nodoc:
class InstallGenerator < ::Rails::Generators::Base
include ::Rails::Generators::Migration
source_root File.expand_path('templates', __dir__)
def self.next_migration_number(path)
ActiveRecord::Generators::Base.next_migration_number(path)
end
def copy_migrations
migration_template 'migration.rb',
'db/migrate/create_letsencrypt_certificates.rb'
end
def copy_config
copy_file 'letsencrypt.rb', 'config/initializers/letsencrypt.rb'
end
def required_migration_version?
Rails::VERSION::MAJOR >= 5
end
def migration_version
"[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]" if required_migration_version?
end
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/generators/lets_encrypt/templates/letsencrypt.rb | lib/generators/lets_encrypt/templates/letsencrypt.rb | LetsEncrypt.config do |config|
# Configure the ACME server
# Default is Let's Encrypt production server
# config.acme_server = 'https://acme-v02.api.letsencrypt.org/directory'
# Using Let's Encrypt staging server or not
# Default only `Rails.env.production? == true` will use Let's Encrypt production server.
# config.use_staging = true
# Set the private key path
# Default is locate at config/letsencrypt.key
config.private_key_path = Rails.root.join('config', 'letsencrypt.key')
# Use environment variable to set private key
# If enable, the API Client will use `LETSENCRYPT_PRIVATE_KEY` as private key
# Default is false
config.use_env_key = false
# Should sync certificate into redis
# When using ngx_mruby to dynamic load certificate, this will be helpful
# Default is false
config.save_to_redis = false
# The redis server url
# Default is nil
config.redis_url = 'redis://localhost:6379/1'
# Enable it if you want to customize the model
# Default is LetsEncrypt::Certificate
# config.certificate_model = 'MyCertificate'
# Configure the maximum attempts to re-check status when verifying or issuing
# config.max_attempts = 30
# Configure the interval between attempts
# config.retry_interval = 1
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/generators/lets_encrypt/templates/migration.rb | lib/generators/lets_encrypt/templates/migration.rb | # frozen_string_literal: true
# :nodoc:
class CreateLetsencryptCertificates < ActiveRecord::Migration<%= migration_version %>
def change
create_table :letsencrypt_certificates do |t|
t.string :domain
t.text :certificate, limit: 65535
t.text :intermediaries, limit: 65535
t.text :key, limit: 65535
t.datetime :expires_at
t.datetime :renew_after
t.string :verification_path
t.string :verification_string
t.index :domain
t.index :renew_after
t.timestamps
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/letsencrypt/version.rb | lib/letsencrypt/version.rb | # frozen_string_literal: true
module LetsEncrypt
VERSION = '0.13.0'
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/letsencrypt/status_checker.rb | lib/letsencrypt/status_checker.rb | # frozen_string_literal: true
module LetsEncrypt
# The status checker to make a loop until the status is reached
class StatusChecker
attr_reader :max_attempts, :interval
def initialize(max_attempts:, interval:)
@max_attempts = max_attempts
@interval = interval
end
def execute
attempts = 0
loop do
break if yield
attempts += 1
raise MaxCheckExceeded, "Max attempts exceeded (#{max_attempts})" if attempts >= max_attempts
sleep interval
end
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.