repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
nsingh/apm-agent-ruby
|
spec/elastic_apm/spies/dynamo_db_spec.rb
|
<reponame>nsingh/apm-agent-ruby
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# frozen_string_literal: true
require 'spec_helper'
require 'aws-sdk-dynamodb'
module ElasticAPM
RSpec.describe 'Spy: DynamoDB' do
let(:dynamo_db_client) do
::Aws::DynamoDB::Client.new(stub_responses: true)
end
it "spans operations", :intercept do
with_agent do
ElasticAPM.with_transaction 'T' do
dynamo_db_client.update_item(table_name: 'test', key: {})
end
end
span = @intercepted.spans.first
expect(span.name).to eq(:update_item)
expect(span.type).to eq('db')
expect(span.subtype).to eq('dynamodb')
expect(span.action).to eq(:update_item)
expect(span.outcome).to eq('success')
end
context 'when the operation fails' do
it 'sets span outcome to `failure`', :intercept do
with_agent do
ElasticAPM.with_transaction do
begin
dynamo_db_client.batch_get_item({})
rescue
end
end
span = @intercepted.spans.first
expect(span.outcome).to eq('failure')
end
end
end
end
end
|
nsingh/apm-agent-ruby
|
lib/elastic_apm/span.rb
|
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# frozen_string_literal: true
require 'elastic_apm/span/context'
module ElasticAPM
# @api private
class Span
extend Forwardable
include ChildDurations::Methods
# @api private
class Outcome
FAILURE = "failure"
SUCCESS = "success"
UNKNOWN = "unknown"
def self.from_http_status(code)
code.to_i >= 400 ? FAILURE : SUCCESS
end
end
DEFAULT_TYPE = 'custom'
# rubocop:disable Metrics/ParameterLists
def initialize(
name:,
transaction:,
trace_context:,
parent:,
type: nil,
subtype: nil,
action: nil,
context: nil,
stacktrace_builder: nil,
sync: nil
)
@name = name
if subtype.nil? && type&.include?('.')
@type, @subtype, @action = type.split('.')
else
@type = type || DEFAULT_TYPE
@subtype = subtype
@action = action
end
@transaction = transaction
@parent = parent
@trace_context = trace_context || parent.trace_context.child
@sample_rate = transaction.sample_rate
@context = context || Span::Context.new(sync: sync)
@stacktrace_builder = stacktrace_builder
end
# rubocop:enable Metrics/ParameterLists
def_delegators :@trace_context, :trace_id, :parent_id, :id
attr_accessor(
:action,
:name,
:original_backtrace,
:outcome,
:subtype,
:trace_context,
:type
)
attr_reader(
:context,
:duration,
:parent,
:sample_rate,
:self_time,
:stacktrace,
:timestamp,
:transaction
)
# life cycle
def start(clock_start = Util.monotonic_micros)
@timestamp = Util.micros
@clock_start = clock_start
@parent.child_started
self
end
def stop(clock_end = Util.monotonic_micros)
@duration ||= (clock_end - @clock_start)
@parent.child_stopped
@self_time = @duration - child_durations.duration
self
end
def done(clock_end: Util.monotonic_micros)
stop clock_end
self
end
def prepare_for_serialization!
build_stacktrace! if should_build_stacktrace?
self.original_backtrace = nil # release original
end
def stopped?
!!duration
end
def started?
!!timestamp
end
def running?
started? && !stopped?
end
# relations
def inspect
"<ElasticAPM::Span id:#{trace_context&.id}" \
" name:#{name.inspect}" \
" type:#{type.inspect}" \
'>'
end
private
def build_stacktrace!
@stacktrace = @stacktrace_builder.build(original_backtrace, type: :span)
end
def should_build_stacktrace?
@stacktrace_builder && original_backtrace && long_enough_for_stacktrace?
end
def long_enough_for_stacktrace?
min_duration =
@stacktrace_builder.config.span_frames_min_duration_us
return true if min_duration < 0
return false if min_duration == 0
duration >= min_duration
end
end
end
|
nsingh/apm-agent-ruby
|
spec/elastic_apm/transport/filters/hash_sanitizer_spec.rb
|
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# frozen_string_literal: true
require 'spec_helper'
module ElasticAPM
module Transport
module Filters
RSpec.describe HashSanitizer do
let(:config) { Config.new }
subject do
described_class.new(
key_patterns: config.custom_key_filters + config.sanitize_field_names
)
end
describe '#strip_from!' do
it 'removes secret keys from requests' do
payload = {
ApiKey: 'very zecret!',
Untouched: 'very much',
TotallyNotACreditCard: '4111 1111 1111 1111',
'HTTP_COOKIE': 'things=1'
}
subject.strip_from!(payload)
expect(payload).to match(
ApiKey: '[FILTERED]',
Untouched: 'very much',
TotallyNotACreditCard: '[FILTERED]',
HTTP_COOKIE: '[FILTERED]'
)
end
it 'works on nested hashes' do
payload = { nested: { ApiKey: '123' } }
subject.strip_from!(payload)
expect(payload.dig(:nested, :ApiKey)).to eq '[FILTERED]'
end
end
describe '#strip_from' do
it 'returns a recursively cloned copy' do
obj = Object.new
payload = { nested: { ApiKey: obj } }
result = subject.strip_from(payload)
expect(result).to match(nested: { ApiKey: Object })
expect(result).to_not be payload
expect(result.dig(:nested, :ApiKey)).to_not be obj
end
end
end
end
end
end
|
nsingh/apm-agent-ruby
|
lib/elastic_apm/spies/dynamo_db.rb
|
<filename>lib/elastic_apm/spies/dynamo_db.rb
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# frozen_string_literal: true
module ElasticAPM
# @api private
module Spies
# @api private
class DynamoDBSpy
def self.without_net_http
return yield unless defined?(NetHTTPSpy)
# rubocop:disable Style/ExplicitBlockArgument
ElasticAPM::Spies::NetHTTPSpy.disable_in do
yield
end
# rubocop:enable Style/ExplicitBlockArgument
end
def install
::Aws::DynamoDB::Client.class_eval do
# Alias all available operations
api.operation_names.each do |operation_name|
alias :"#{operation_name}_without_apm" :"#{operation_name}"
define_method(operation_name) do |params = {}, options = {}|
ElasticAPM.with_span(
operation_name,
'db',
subtype: 'dynamodb',
action: operation_name
) do
ElasticAPM::Spies::DynamoDBSpy.without_net_http do
original_method = method("#{operation_name}_without_apm")
original_method.call(params, options)
end
end
end
end
end
end
end
register(
'Aws::DynamoDB::Client',
'aws-sdk-dynamodb',
DynamoDBSpy.new
)
end
end
|
fidor/fidor_api
|
spec/lib/fidor_api/token_spec.rb
|
require 'spec_helper'
module FidorApi
RSpec.describe Token do
let(:instance) { described_class.new(attributes) }
let(:attributes) do
{
access_token: 'access-token',
expires_in: 900,
token_type: 'Bearer',
refresh_token: '<PASSWORD>-<PASSWORD>'
}
end
describe '#to_h' do
it 'returns all attributes in one hash' do
expect(instance.to_h).to eq attributes
end
context 'when the token contains extra attributes' do
let(:attributes_with_extra) do
{
access_token: 'access-token',
expires_in: 900,
token_type: 'Bearer',
refresh_token: '<PASSWORD>-token',
extra_attribute: 'value'
}
end
let(:instance) { described_class.new(attributes_with_extra) }
it 'returns all attributes in one hash and ignores the extra undefined ones' do
expect(instance.to_h).to eq attributes
end
end
end
end
end
|
corpitsysadmins/bind-formula
|
test/integration/default/controls/zones_spec.rb
|
<reponame>corpitsysadmins/bind-formula<gh_stars>0
# Set defaults, use debian as base
conf_user = 'bind'
conf_group = 'bind'
keys_user = 'root'
keys_group = conf_group
logs_user = 'root'
logs_group = conf_group
named_directory = '/var/cache/bind'
zones_directory = '/var/cache/bind/zones'
keys_directory = '/etc/bind/keys'
log_directory = '/var/log/bind9'
keys_mode = '02755'
conf_mode = '0644'
config = '/etc/bind/named.conf'
# Override by OS
case os[:name]
when 'arch','redhat', 'centos', 'fedora', 'amazon'
conf_user = 'named'
conf_group = 'named'
keys_group = 'root'
logs_group = conf_group
named_directory = '/var/named'
zones_directory = named_directory
keys_directory = '/etc/named.keys'
keys_mode = '0755'
conf_mode = '0640'
config = '/etc/named.conf'
when 'suse', 'opensuse'
zones_directory = nil # not implemented
end
# Override log directory by OS
case os[:name]
when 'arch', 'ubuntu'
log_directory = '/var/log/named'
when 'redhat', 'centos', 'fedora', 'amazon'
log_directory = '/var/named/data'
end
if zones_directory
# Test example.com zonefile
control 'File ' + zones_directory + '/example.com' do
title 'should exist'
describe file(zones_directory + '/example.com') do
its('owner') { should eq conf_user }
its('group') { should eq conf_group }
its('mode') { should cmp '0644' }
# Multi line regex to match the various zones
# If you're here to update the pillar/tests I would highly reccommend
# using an online miltiline regex editor to do this:
# https://www.regextester.com/
# the #{foo} is a ruby string expansion so we can use the variables
# defined above
# Match SOA
its('content') { should match /^@\ IN\ SOA\ ns1.example.com\ hostmaster.example.com\ \(\n 2018073100\ ;\ serial\n\ \ \ \ 12h\ ;\ refresh\n\ \ \ \ 600\ ;\ retry\n\ \ \ \ 2w\ ;\ expiry\n\ \ \ \ 1m\ ;\ nxdomain\ ttl\n\);/ }
# Just match string for these as it's much easier to read
# Match NS
its('content') { should match '@ NS ns1' }
# Match A
its('content') { should match 'ns1 A 203.0.113.1' }
its('content') { should match 'foo A 203.0.113.2' }
its('content') { should match 'bar A 203.0.113.3' }
# Match CNAME
its('content') { should match 'ftp CNAME foo.example.com.' }
its('content') { should match 'www CNAME bar.example.com.' }
its('content') { should match 'mail CNAME mx1.example.com.' }
its('content') { should match 'smtp CNAME mx1.example.com.' }
# Match TXT
its('content') { should match '@ TXT "some_value"' }
end
end
# Test example.net zonefile
control 'File ' + zones_directory + '/example.net' do
title 'should exist'
describe file(zones_directory + '/example.net') do
its('owner') { should eq conf_user }
its('group') { should eq conf_group }
its('mode') { should cmp '0644' }
# Match SOA
its('content') { should match /^@\ IN\ SOA\ ns1.example.net\ hostmaster.example.net\ \(\n\ \ \ \ [0-9]{10}\ ;\ serial\n\ \ \ \ 12h\ ;\ refresh\n\ \ \ \ 300\ ;\ retry\n\ \ \ \ 2w\ ;\ expiry\n\ \ \ \ 1m\ ;\ nxdomain\ ttl\n\);/ }
# Match Include
its('content') { should match /^\$INCLUDE\ #{zones_directory}\/example\.net\.include$/ }
end
end
# Test example.net.include zonefile
control 'File ' + zones_directory + '/example.net.include' do
title 'should exist'
describe file(zones_directory + '/example.net.include') do
its('owner') { should eq conf_user }
its('group') { should eq conf_group }
its('mode') { should cmp '0644' }
# Just match string for these as it's much easier to read
# Match NS
its('content') { should match '@ NS ns1' }
# Match A
its('content') { should match 'ns1 A 198.51.100.1' }
its('content') { should match 'foo A 198.51.100.2' }
its('content') { should match 'bar A 198.51.100.3' }
its('content') { should match 'baz A 198.51.100.4' }
its('content') { should match 'mx1 A 198.51.100.5' }
its('content') { should match 'mx1 A 198.51.100.6' }
its('content') { should match 'mx1 A 198.51.100.7' }
# Match CNAME
its('content') { should match 'mail CNAME mx1.example.net.' }
its('content') { should match 'smtp CNAME mx1.example.net.' }
end
end
# Test 113.0.203.in-addr.arpa zonefile
control 'File ' + zones_directory + '/113.0.203.in-addr.arpa' do
title 'should exist'
describe file(zones_directory + '/113.0.203.in-addr.arpa') do
its('owner') { should eq conf_user }
its('group') { should eq conf_group }
its('mode') { should cmp '0644' }
# Match SOA
its('content') { should match /^@\ IN\ SOA\ ns1.example.com\ hostmaster.example.com\ \(\n\ \ \ \ 2018073100\ ;\ serial\n\ \ \ \ 12h\ ;\ refresh\n\ \ \ \ 600\ ;\ retry\n\ \ \ \ 2w\ ;\ expiry\n\ \ \ \ 1m\ ;\ nxdomain\ ttl\n\);/ }
# Just match string for these as it's much easier to read
# Match Include
its('content') { should match '172.16.31.10.in-addr.arpa PTR ns1.example.com.' }
its('content') { should match '192.168.127.12.in-addr.arpa PTR foo.example.com.' }
its('content') { should match '172.16.58.3.in-addr.arpa PTR bar.example.com.' }
end
end
# Test 100.51.198.in-addr.arpa zonefile
control 'File ' + zones_directory + '/100.51.198.in-addr.arpa' do
title 'should exist'
describe file(zones_directory + '/100.51.198.in-addr.arpa') do
its('owner') { should eq conf_user }
its('group') { should eq conf_group }
its('mode') { should cmp '0644' }
# Match SOA
its('content') { should match /^@\ IN\ SOA\ ns1.example.net\ hostmaster.example.net\ \(\n\ \ \ \ [0-9]{10}\ ;\ serial\n\ \ \ \ 12h\ ;\ refresh\n\ \ \ \ 600\ ;\ retry\n\ \ \ \ 2w\ ;\ expiry\n\ \ \ \ 1m\ ;\ nxdomain\ ttl\n\);/ }
# Match Include
its('content') { should match /^\$INCLUDE\ #{zones_directory}\/100\.51\.198\.in-addr\.arpa\.include$/ }
end
end
# Test 100.51.198.in-addr.arpa.include zonefile
control 'File ' + zones_directory + '/100.51.198.in-addr.arpa.include' do
title 'should exist'
describe file(zones_directory + '/100.51.198.in-addr.arpa.include') do
its('owner') { should eq conf_user }
its('group') { should eq conf_group }
its('mode') { should cmp '0644' }
# Match PTR
its('content') { should match '172.16.17.32.in-addr.arpa. PTR ns1.example.net.' }
its('content') { should match '192.168.127.12.in-addr.arpa. PTR foo.example.net.' }
its('content') { should match '172.16.17.32.in-addr.arpa. PTR bar.example.net.' }
its('content') { should match '172.16.58.3.in-addr.arpa. PTR baz.example.net.' }
its('content') { should match '172.16.17.32.in-addr.arpa. PTR mx1.example.net.' }
its('content') { should match '192.168.3.11.in-addr.arpa. PTR mx1.example.net.' }
its('content') { should match '192.168.127.12.in-addr.arpa. PTR mx1.example.net.' }
end
end
end
|
DouweBos/DJBExtensionKit
|
DJBExtensionKit.podspec
|
<gh_stars>0
#
# Be sure to run `pod lib lint DJBExtensionKit.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'DJBExtensionKit'
s.version = '0.4.17'
s.summary = 'Collection of personal extension I like to use.'
s.description = <<-DESC
Just a collection of extensions I like to use. This is just so I no longer have to copy everything over from project to project. Please do not actually use me.
DESC
s.homepage = 'https://github.com/DouweBos/DJBExtensionKit'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'DouweBos' => '<EMAIL>' }
s.source = { :git => 'https://github.com/DouweBos/DJBExtensionKit.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/douwebos_nl'
s.platform = :ios, :tvos
s.ios.deployment_target = '10.0'
s.tvos.deployment_target = '10.0'
s.swift_version = '5.1'
s.default_subspec = 'Core'
s.subspec 'Core' do |ss|
ss.source_files = 'DJBExtensionKit/Classes/Core/**/*'
end
s.subspec 'RxSwift' do |ss|
ss.source_files = 'DJBExtensionKit/Classes/RxSwift/**/*'
ss.dependency 'DJBExtensionKit/Core', "~> #{s.version}"
ss.dependency 'RxSwift', '~> 6'
ss.dependency 'RxSwift', '~> 6'
ss.dependency 'RxSwiftExt', '~> 6'
ss.dependency 'RxCocoa', '~> 6'
end
s.subspec 'Kingfisher' do |ss|
ss.source_files = 'DJBExtensionKit/Classes/Kingfisher/**/*'
ss.dependency 'DJBExtensionKit/Core', "~> #{s.version}"
ss.dependency 'Kingfisher', '~> 5'
ss.dependency 'RxKingfisher'
end
s.subspec 'Nuke' do |ss|
ss.source_files = 'DJBExtensionKit/Classes/Nuke/**/*'
ss.ios.deployment_target = '11.0'
ss.dependency 'DJBExtensionKit/Core', "~> #{s.version}"
ss.dependency 'Nuke', '~> 9'
ss.dependency 'RxNuke', '~> 1'
end
end
|
osu-cascades/bethlehem-inn-inkeeper
|
db/seeds.rb
|
<filename>db/seeds.rb
User.create(
email: '<EMAIL>',
password: 'password',
password_confirmation: 'password',
first_name: 'Developer',
last_name: 'Admin',
role: :admin
)
puts "Default admin user created with email '<EMAIL>' and password 'password'."
|
evendis/gmail_cli
|
spec/unit/imap_spec.rb
|
<filename>spec/unit/imap_spec.rb
require 'spec_helper'
describe GmailCli do
let(:options) { {} }
describe "##imap_connection" do
subject { GmailCli.imap_connection(options) }
it "returns a connected GmailCli::Imap" do
expect_any_instance_of(GmailCli::Imap).to receive(:connect!).and_return('result!')
expect(subject).to eql('result!')
end
end
describe "::Imap" do
let(:imap) { GmailCli::Imap.new(options) }
subject { imap }
it "has the expected default settings" do
expect(subject.username).to be_nil
expect(subject.host).to eql('imap.gmail.com')
expect(subject.host_options).to eql({port: 993, ssl: true})
end
describe "#username" do
let(:expected) { '<EMAIL>' }
let(:options) { {username: expected} }
it "can be set through options" do
expect(subject.username).to eql(expected)
end
end
describe "#host" do
let(:expected) { 'test.com' }
let(:options) { {host: expected} }
it "can be set through options" do
expect(subject.host).to eql(expected)
end
end
describe "#host_options" do
let(:expected) { {port: 111} }
let(:options) { {host_options: expected} }
it "can be set through options" do
expect(subject.host_options).to eql(expected)
end
end
describe "#oauth_options" do
it "is all nil by default" do
expect(subject.oauth_options).to eql({
client_id: nil,
client_secret: nil,
access_token: nil,
refresh_token: nil
})
end
context "when some given in options" do
let(:options) { {client_id: 'abcd'} }
it "sets selected items correctly" do
expect(subject.oauth_options).to eql({
client_id: 'abcd',
client_secret: nil,
access_token: nil,
refresh_token: nil
})
end
end
context "when all given in options" do
let(:options) { {client_id: 'abcd', client_secret: 'efg', access_token: '<PASSWORD>', refresh_token: '<PASSWORD>'} }
it "sets all items correctly" do
expect(subject.oauth_options).to eql({
client_id: 'abcd',
client_secret: 'efg',
access_token: '<PASSWORD>',
refresh_token: '<PASSWORD>'
})
expect(subject.options.keys).to_not include(:client_id)
expect(subject.oauth_access_token).to eql('<PASSWORD>')
end
end
end
end
end
|
evendis/gmail_cli
|
spec/unit/logger_spec.rb
|
<reponame>evendis/gmail_cli
require 'spec_helper'
describe GmailCli::Logger do
let(:logger) { GmailCli::Logger }
let(:trace_something) { logger.trace 'somthing', 'bogative' }
it "does not log when verbose mode not enabled" do
expect($stderr).to receive(:puts).never
trace_something
end
it "logs when verbose mode enabled" do
logger.set_log_mode(true)
expect($stderr).to receive(:puts).and_return(nil)
trace_something
logger.set_log_mode(false)
end
it "does not log when verbose mode enabled then disabled" do
logger.set_log_mode(true)
logger.set_log_mode(false)
expect($stderr).to receive(:puts).never
trace_something
end
end
|
evendis/gmail_cli
|
spec/unit/oauth2_helper_spec.rb
|
<reponame>evendis/gmail_cli
require 'spec_helper'
describe GmailCli::Oauth2Helper do
let(:resource_class) { GmailCli::Oauth2Helper }
let(:instance) { resource_class.new(options) }
let(:options) { {} }
let(:expected) { 'canary' }
before do
# silence echo
allow_any_instance_of(resource_class).to receive(:echo).and_return(nil)
end
describe "##authorize!" do
subject { resource_class.authorize!(options) }
it "invokes authorize! on instance" do
expect_any_instance_of(resource_class).to receive(:authorize!).and_return('result!')
expect(subject).to eql('result!')
end
end
describe "#client_id" do
subject { instance.client_id }
it "is nil by default" do
expect(subject).to be_nil
end
context "when given in options" do
let(:options) { {client_id: expected} }
it "returns the setting" do
expect(subject).to eql(expected)
end
end
end
describe "#client_secret" do
subject { instance.client_secret }
it "is nil by default" do
expect(subject).to be_nil
end
context "when given in options" do
let(:options) { {client_secret: expected} }
it "returns the setting" do
expect(subject).to eql(expected)
end
end
end
describe "#authorization_code" do
subject { instance.authorization_code }
it "is nil by default" do
expect(subject).to be_nil
end
context "cannot be given in options" do
let(:options) { {authorization_code: expected} }
it { should be_nil }
end
end
describe "#access_token" do
subject { instance.access_token }
it "is nil by default" do
expect(subject).to be_nil
end
context "when given in options" do
let(:options) { {access_token: expected} }
it "returns the setting" do
expect(subject).to eql(expected)
end
end
end
describe "#refresh_token" do
subject { instance.refresh_token }
it "is nil by default" do
expect(subject).to be_nil
end
context "when given in options" do
let(:options) { {refresh_token: expected} }
it "returns the setting" do
expect(subject).to eql(expected)
end
end
end
describe "#scope" do
subject { instance.scope }
it "is set by default" do
expect(subject).to eql('https://mail.google.com/')
end
context "when given in options" do
let(:options) { {scope: expected} }
it "returns the setting" do
expect(subject).to eql(expected)
end
end
end
describe "#redirect_uri" do
subject { instance.redirect_uri }
it "is set by default" do
expect(subject).to eql('urn:ietf:wg:oauth:2.0:oob')
end
context "when given in options" do
let(:options) { {redirect_uri: expected} }
it "returns the setting" do
expect(subject).to eql(expected)
end
end
end
describe "#application_name" do
subject { instance.application_name }
it "is set by default" do
expect(subject).to eql('gmail_cli')
end
context "when given in options" do
let(:options) { {application_name: expected} }
it "returns the setting" do
expect(subject).to eql(expected)
end
end
end
describe "#application_version" do
subject { instance.application_version }
it "is set by default" do
expect(subject).to eql(GmailCli::VERSION)
end
context "when given in options" do
let(:options) { {application_version: expected} }
it "returns the setting" do
expect(subject).to eql(expected)
end
end
end
describe "#ensure_provided" do
let(:key) { :client_id }
subject { instance.ensure_provided(key) }
context "when value already set" do
let(:options) { {client_id: 'set'} }
it "should not ask_for_entry when already set" do
expect(instance).to receive(:ask_for_entry).never
subject
end
end
context "when value not already set" do
it "should ask_for_entry when already set" do
expect(instance).to receive(:ask_for_entry).and_return('got it')
subject
end
end
end
describe "#authorize!" do
subject { instance.authorize! }
it "invokes get_access_token" do
expect(instance).to receive(:get_access_token!).and_return(nil)
subject
end
end
describe "#api_client" do
let(:options) { {client_id: 'client_id', client_secret: 'client_secret'} }
subject { instance.api_client }
it "returns an initialised Google API client" do
expect(subject).to be_a(Google::APIClient)
end
end
describe "#get_access_token!" do
let(:options) { {client_id: 'client_id', client_secret: 'client_secret'} }
let(:mock_access_token) { "<KEY>" }
let(:mock_refresh_token) { "<KEY>" }
let(:mock_fetch_access_token_response) { {"access_token"=>mock_access_token, "token_type"=>"Bearer", "expires_in"=>3600, "refresh_token"=>mock_refresh_token} }
subject { instance.get_access_token! }
it "orchestrates the fetch_access_token process correctly" do
expect(instance.api_client).to be_a(Google::APIClient)
expect(instance).to receive(:get_authorization_uri).and_return('http://here')
expect(instance).to receive(:ensure_provided).with(:authorization_code).and_return('authorization_code')
expect(instance).to receive(:fetch_access_token!).and_return(mock_fetch_access_token_response)
expect(subject).to eql(mock_access_token)
expect(instance.access_token).to eql(mock_access_token)
expect(instance.refresh_token).to eql(mock_refresh_token)
end
end
describe "#refresh_access_token!" do
let(:options) { {client_id: 'client_id', client_secret: 'client_secret', refresh_token: mock_refresh_token} }
let(:mock_access_token) { "<KEY>" }
let(:mock_refresh_token) { "<KEY>" }
let(:mock_fetch_refresh_token_response) { {"access_token"=>mock_access_token, "token_type"=>"Bearer", "expires_in"=>3600} }
subject { instance.refresh_access_token! }
it "orchestrates the fetch_access_token process correctly" do
expect(instance.api_client).to be_a(Google::APIClient)
expect(instance).to receive(:fetch_refresh_token!).and_return(mock_fetch_refresh_token_response)
expect(subject).to eql(mock_access_token)
expect(instance.access_token).to eql(mock_access_token)
expect(instance.refresh_token).to eql(mock_refresh_token)
end
end
end
|
evendis/gmail_cli
|
lib/gmail_cli/imap.rb
|
<gh_stars>1-10
require 'net/imap'
require 'net/http'
require 'uri'
require 'gmail_xoauth'
module GmailCli
# Command: convenience method to return IMAP connection given +options+
def self.imap_connection(options={})
GmailCli::Imap.new(options).connect!
end
class Imap
include GmailCli::LoggerSupport
attr_accessor :imap, :options, :oauth_options
def initialize(options={})
options = options.dup
@oauth_options = {
client_id: options.delete(:client_id),
client_secret: options.delete(:client_secret),
access_token: options.delete(:access_token),
refresh_token: options.delete(:refresh_token)
}
@options = {
host: 'imap.gmail.com'
}.merge(options)
@options[:host_options] ||= {
port: 993,
ssl: true
}
end
def refresh_access_token!
oauth_options[:access_token] = GmailCli::Oauth2Helper.new(oauth_options).refresh_access_token!
end
def host
options[:host]
end
def username
options[:username]
end
def host_options
options[:host_options]
end
def oauth_access_token
oauth_options[:access_token]
end
def connect!
disconnect!
refresh_access_token! # we cheat a bit here - refreshing the token every time we get a new connection
trace "#{__method__} to host", host
self.imap = Net::IMAP.new(host,host_options)
trace "imap capabilities", imap.capability
imap.authenticate('XOAUTH2', username, oauth_access_token)
imap
end
def disconnect!
return unless imap
trace "calling", __method__
imap.close
self.imap = nil
rescue Exception => e
trace "#{__method__} error", e
end
end
end
|
evendis/gmail_cli
|
lib/gmail_cli/oauth2_helper.rb
|
<reponame>evendis/gmail_cli
require 'google/api_client'
class GmailCli::Oauth2Helper
include GmailCli::LoggerSupport
class << self
# Command: convenience class method to invoke authorization phase
def authorize!(options={})
new(options).authorize!
rescue Interrupt
$stderr.puts "..interrupted."
end
end
attr_accessor :client_id, :client_secret
attr_accessor :authorization_code, :access_token, :refresh_token
attr_accessor :scope, :redirect_uri, :application_name, :application_version
def initialize(options={})
@client_id = options[:client_id]
@client_secret = options[:client_secret]
@access_token = options[:access_token]
@refresh_token = options[:refresh_token]
@scope = options[:scope] || 'https://mail.google.com/'
@redirect_uri = options[:redirect_uri] || 'urn:ietf:wg:oauth:2.0:oob'
@application_name = options[:application_name] || 'gmail_cli'
@application_version = options[:application_version] || GmailCli::VERSION
trace "#{self.class.name} resolved options", {
client_id: client_id, client_secret: client_secret,
access_token: access_token, refresh_token: refresh_token,
scope: scope, redirect_uri: redirect_uri,
application_name: application_name, application_version: application_version
}
end
def echo(text)
puts text
end
# Command: requests and returns a fresh access_token
def refresh_access_token!
api_client.authorization.refresh_token = refresh_token
response = fetch_refresh_token!
# => {"access_token"=>"<KEY>", "token_type"=>"Bearer", "expires_in"=>3600}
trace "#{__method__} response", response
self.access_token = response['access_token']
end
# Command: runs an interactive authorization phase
def authorize!
echo %(
Performing Google OAuth2 client authorization
---------------------------------------------)
get_access_token!
end
def api_client
@api_client ||= if ensure_provided(:client_id) && ensure_provided(:client_secret) && ensure_provided(:redirect_uri) && ensure_provided(:scope)
# Initialize OAuth 2.0 client
api_client = Google::APIClient.new(application_name: application_name, application_version: application_version)
api_client.authorization.client_id = client_id
api_client.authorization.client_secret = client_secret
api_client.authorization.redirect_uri = redirect_uri
api_client.authorization.scope = scope
api_client
end
end
def get_access_token!
# Request authorization
authorization_uri = get_authorization_uri
echo %(
Go to the following URL in a web browser to grant the authorization.
There you will be able to select specifically which gmail account the authorization is for.
#{authorization_uri}
When you have done that successfully it will provide a code to enter here:
)
api_client.authorization.code = ensure_provided(:authorization_code)
response = fetch_access_token!
# => {"access_token"=>"<KEY>", "token_type"=>"Bearer", "expires_in"=>3600, "refresh_token"=>"<KEY>"}
trace "#{__method__} response", response
self.access_token = response['access_token']
self.refresh_token = response['refresh_token']
echo %(
Authorization was successful! You can now use this credential to access gmail.
For example, to get an authenticated IMAP connection to the '<EMAIL>' account:
credentials = {
client_id: '#{client_id}',
client_secret: '#{client_secret}',
access_token: '#{access_token}',
refresh_token: '#{refresh_token}',
username: '<EMAIL>'
}
imap = GmailCli.imap_connection(credentials)
)
access_token
end
def get_authorization_uri
api_client.authorization.authorization_uri
end
def fetch_access_token!
api_client.authorization.fetch_access_token!
end
def fetch_refresh_token!
api_client.authorization.refresh!
end
def ensure_provided(key)
eval("self.#{key} ||= ask_for_entry('#{key}: ')")
end
def ask_for_entry(prompt)
print prompt
STDIN.gets.chomp!
end
end
|
evendis/gmail_cli
|
spec/unit/tasks_spec.rb
|
<reponame>evendis/gmail_cli<filename>spec/unit/tasks_spec.rb
require 'spec_helper'
describe "Rake Task gmail_cli:" do
require 'rake'
require 'gmail_cli/tasks'
describe "authorize" do
let(:task_name) { "gmail_cli:authorize" }
let :run_rake_task do
Rake::Task[task_name].reenable
Rake.application.invoke_task task_name
end
it "runs successfully" do
expect_any_instance_of(GmailCli::Oauth2Helper).to receive(:authorize!).and_return(nil)
expect { run_rake_task }.to_not raise_error
end
end
end
|
evendis/gmail_cli
|
lib/gmail_cli/logger.rb
|
class GmailCli::Logger
class << self
def log(msg)
$stdout.puts "#{Time.now}| #{msg}"
end
def trace(name,value) ; value ; end
def set_log_mode(verbose)
if verbose
class_eval <<-LOGGER_ACTION, __FILE__, __LINE__
def self.trace(name,value)
$stderr.puts "\#{Time.now}| \#{name}: \#{value.inspect}"
value
end
LOGGER_ACTION
else
class_eval <<-LOGGER_ACTION, __FILE__, __LINE__
def self.trace(name,value) ; value ; end
LOGGER_ACTION
end
end
end
end
module GmailCli::LoggerSupport
def trace(name,value)
GmailCli::Logger.trace name,value
end
def log(msg)
GmailCli::Logger.log msg
end
end
|
evendis/gmail_cli
|
lib/gmail_cli/tasks.rb
|
namespace :gmail_cli do
require 'gmail_cli'
desc "Perform Google OAuth2 client authorization with client_id=? client_secret=?"
task :authorize do |t|
options = {
client_id: ENV['client_id'],
client_secret: ENV['client_secret'],
scope: ENV['scope'],
redirect_uri: ENV['redirect_uri'],
application_name: ENV['application_name'],
application_version: ENV['application_version']
}
GmailCli::Logger.set_log_mode(t.application.options.trace)
GmailCli::Oauth2Helper.authorize!(options)
end
end
|
evendis/gmail_cli
|
lib/gmail_cli/shell.rb
|
<reponame>evendis/gmail_cli
# class that groks the command line options and invokes the required task
class GmailCli::Shell
# holds the parsed options
attr_reader :options
# holds the remaining command line arguments
attr_reader :args
# initializes the shell with command line argments:
#
# +options+ is expected to be the hash structure as provided by GetOptions.new(..)
#
# +args+ is the remaining command line arguments
#
def initialize(options,args)
@options = (options||{}).each{|k,v| {k => v} }
@args = args
GmailCli::Logger.set_log_mode(options[:verbose])
end
# Command: execute the task according to the options provided on initialisation
def run
case
when args.first =~ /authorize/i
authorize
else
usage
end
end
# defines the valid command line options
OPTIONS = %w(help verbose client_id:s client_secret:s)
class << self
# prints usage/help information
def usage
$stderr.puts <<-EOS
GmailCli v#{GmailCli::VERSION}
===================================
Usage:
gmail_cli [options] [commands]
Options:
-h | --help : shows command help
-v | --verbose : run with verbose
--client_id "xxxx" : OAuth2 client_id
--client_secret "yyy" : OAuth2 client_secret
Commands:
authorize : perform Google OAuth2 client authorization
EOS
end
end
# prints usage/help information
def usage
self.class.usage
end
def authorize
GmailCli::Oauth2Helper.authorize!(options)
end
end
|
evendis/gmail_cli
|
lib/gmail_cli.rb
|
<filename>lib/gmail_cli.rb<gh_stars>1-10
require "gmail_cli/version"
require "gmail_cli/logger"
require "gmail_cli/oauth2_helper"
require "gmail_cli/shell"
require "gmail_cli/imap"
|
evendis/gmail_cli
|
spec/unit/shell_spec.rb
|
require 'spec_helper'
require 'getoptions'
describe GmailCli::Shell do
let(:getoptions) { GetOptions.new(GmailCli::Shell::OPTIONS, options) }
let(:shell) { GmailCli::Shell.new(getoptions,argv) }
before do
allow($stderr).to receive(:puts) # silence console feedback chatter
end
describe "#usage" do
let(:options) { ['-h'] }
let(:argv) { [] }
it "prints usage when run" do
expect(shell).to receive(:usage)
shell.run
end
end
describe "#authorize" do
let(:options) { [] }
let(:argv) { ["authorize"] }
it "should invoke authorize when run" do
expect(GmailCli::Oauth2Helper).to receive(:authorize!)
shell.run
end
end
end
|
KaanOzkan/rails-i18n
|
lib/rails_i18n.rb
|
<reponame>KaanOzkan/rails-i18n
require 'rails_i18n/unicode'
require 'rails_i18n/railtie'
|
KaanOzkan/rails-i18n
|
lib/rails_i18n/unicode.rb
|
$KCODE = "U" if RUBY_VERSION < '1.9' && $KCODE == 'NONE'
|
cheerharry90/TestPodSDK
|
TestPodSDK.podspec
|
Pod::Spec.new do |s|
#名称
s.name = 'TestPodSDK'
#版本号
s.version = '1.0.0'
#许可证
s.license = { :type => 'MIT' }
#项目主页地址
s.homepage = 'https://github.com/cheerharry90/TestPodSDK.git'
#作者
s.author = { "cheer_harry" => "<EMAIL>" }
#简介
s.summary = 'A delightful iOS framework.'
#项目的地址 (注意这里的tag位置,可以自己写也可以直接用s.version,但是与s.version一定要统一)
s.source = { :git => "https://github.com/cheerharry90/TestPodSDK.git", :tag => s.version}
#支持最小系统版本
s.platform = :ios, ‘8.0’
#需要包含的源文件
s.source_files = 'TestPodSDK/TestPodSDK.framework/Headers/*.{h}'
#你的SDK路径
s.vendored_frameworks = 'TestPodSDK/TestPodSDK.framework'
#SDK头文件路径
s.public_header_files = 'TestPodSDK/TestPodSDK.framework/Headers/TestPodSDK.h'
#依赖库
#依赖库
s.frameworks = 'UIKit','Foundation'
end
|
netguru-hackathon/toggler
|
command_line/handler.rb
|
<gh_stars>0
require_relative "parser"
module CommandLine
class Handler
attr_accessor :command, :params, :options, :project, :task
def initialize
@params = ARGV
@command = params.shift
assign_project_and_task(params.shift) unless params[0]&.start_with?("-")
@options = Parser.parse params
end
def call
run_command
end
private
def assign_project_and_task(value)
return if value.nil?
@project, @task = value.split("/")
end
def run_command
case command
when "start" then task_start
when "stop" then task_stop
when "list" then fetch_list
when "current" then fetch_current
when "summary" then fetch_summary
else command_not_found
end
end
def task_start
entry_params = {
description: options.description,
task_name: task,
project_name: project,
billable: options.billable,
workspace_name: options.workspace
}
puts Toggler::TogglManager.new.start_entry(entry_params)
end
def task_stop
puts Toggler::TogglManager.new.stop_entry
end
def fetch_list
Toggler::TogglManager.new.list_projects_with_tasks.each{ |project_info| puts project_info }
end
def fetch_current
puts Toggler::TogglManager.new.current_time_entry
end
def fetch_summary
entry_params = {
workspace_name: nil
}
#summary current
puts Toggler::TogglManager.new.summary(entry_params)
end
def command_not_found
puts """
Command not found
start [[project]/[task]] - to start entry
stop - to stop current entry
list - to fetch all project entries
current - show current time entry
summary [*description*] - show summary of entry (default current)
"""
puts CommandLine::Parser.parse %w[--help]
end
end
end
|
netguru-hackathon/toggler
|
command_line/parser.rb
|
<filename>command_line/parser.rb
require "optparse"
module CommandLine
Options = Struct.new(:description, :workspace, :billable)
class Parser
def self.parse(options)
args = Options.new
opt_parser = OptionParser.new do |opts|
opts.banner = "Usage: toggler [options]"
opts.on("-dDESCRIPTION", "--description=DESCRIPTION", "Add description to new entry") do |d|
args.description = d
end
opts.on("-wWORKSPACE", "--workspace=WORKSPACE", "Add description to new entry") do |w|
args.workspace = w
end
opts.on("-b", "--billable", "Set entry to billable (default non billable)") do
args.billable = true
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
end
opt_parser.parse!(options)
return args
end
end
end
|
netguru-hackathon/toggler
|
toggl_manager.rb
|
<reponame>netguru-hackathon/toggler
module Toggler
class TogglManager
def initialize
@config = YAML::load_file("config.yml")
init_api
load_defaults
end
def start_entry(description:, task_name:, project_name:, billable:, workspace_name:)
project_name ||= default_project["name"]
billable ||= default_billable
workspace_name ||= default_workspace["name"]
new_entry_attributes = {
"wid" => workspace_id(workspace_name),
"pid" => project_id(workspace_name, project_name),
"billable" => billable,
"duration" => Time.now.to_i * -1,
"start" => @api.iso8601(Time.now.to_datetime),
"created_with" => "toggler",
}
new_entry_attributes["description"] = description if description
new_entry_attributes["tid"] = task_id(workspace_name, project_name, task_name) if task_name
return "time entry started" if api.create_time_entry(new_entry_attributes)
"error adding time entry"
end
def stop_entry
time_entry_id = api.get_current_time_entry&.[]("id")
return "no running time entry" unless time_entry_id
return "time entry stopped" if api.stop_time_entry(time_entry_id)
"error stopping time entry"
end
def list_projects_with_tasks(workspace_name = default_workspace["name"])
projects_with_tasks(workspace_id(workspace_name))
end
def current_time_entry
current_time_entry = api.get_current_time_entry
return "no time entry started" if current_time_entry.nil?
time_from_start = count_time(Time.parse(current_time_entry['start']))
return show_time_entry(current_time_entry, time_from_start)
"error getting time entry"
end
def summary(workspace_name:)
workspace_name ||= default_workspace["name"]
@reports_api.workspace_id = workspace_id(workspace_name)
entry = api.get_current_time_entry
total_time = @reports_api
.details
.select { |e| e["description"] == entry["description"] && e["pid"] == entry["pid"] }
.map{|e| Time.parse(e["end"]) - Time.parse(e["start"])}
.inject(0, :+)
show_time_entry(entry, total_time)
end
private
attr_reader :api, :user, :workspaces, :default_billable, :default_project, :default_workspace
def init_api
@api_key = @config["toggl_api_key"]
@api = TogglV8::API.new(@api_key)
@reports_api = TogglV8::ReportsV2.new(api_token: @api_key)
@user = api.me(true)
@workspaces = api.my_workspaces(user)
end
def load_defaults
@default_billable = @config["billable_by_default"];
@default_workspace = {
"id" => workspace_id(@config["default_workspace_name"]),
"name" => @config["default_workspace_name"]
}
@default_project = {
"id" => project_id(@default_workspace["name"], @config["default_project_name"]),
"name" => @config["default_project_name"]
}
end
def list_projects(workspace_name = default_workspace["name"])
wid = workspace_id(workspace_name)
api.projects(wid)
end
def projects_with_tasks(wid)
projects = api.projects(wid)
tasks = api.tasks(wid)
project_with_tasks = projects.map do |project|
project_name = project["name"]
project_tasks = tasks.select{ |task| task["pid"] == project["id"] }.map{ |taks| taks["name"] }
"#{project_name}: \n\t#{project_tasks.join(', ')}"
end
end
def workspace_id(workspace_name)
workspaces.find { |w| w["name"] == workspace_name }["id"]
end
def project_id(workspace_name, project_name)
list_projects(workspace_name)
.find { |p| p["name"] == project_name }["id"]
end
def task_id(workspace_name, project_name, task_name)
wid = workspace_id(workspace_name)
pid = project_id(workspace_name, project_name)
api.tasks(wid)
.find { |t| t["pid"] == pid && t["name"] == task_name }["id"]
end
def show_time_entry(entry, time)
project_name = api.get_project(entry['pid'])['name']
"#{entry['description']} |#{project_name}| #{parse_time(time)}"
end
def count_time(start_time)
Time.now - start_time
end
def parse_time(sec)
min, sec = sec.divmod(60)
hour, min = min.divmod(60)
"%02d:%02d:%02d" % [hour, min, sec]
end
end
end
|
noelmcloughlin/insomnia-formula
|
test/integration/binary/controls/binary_spec.rb
|
<gh_stars>1-10
# frozen_string_literal: true
title 'insomnia archives profile'
control 'insomnia archive archive' do
impact 1.0
title 'should be installed'
end
|
Kadenze/carrierwave
|
spec/orm/activerecord_spec.rb
|
require 'spec_helper'
require 'support/activerecord'
def create_table(name)
ActiveRecord::Base.connection.create_table(name, force: true) do |t|
t.column :image, :string
t.column :images, :json
t.column :textfile, :string
t.column :textfiles, :json
t.column :foo, :string
end
end
def drop_table(name)
ActiveRecord::Base.connection.drop_table(name)
end
def reset_class(class_name)
Object.send(:remove_const, class_name) rescue nil
Object.const_set(class_name, Class.new(ActiveRecord::Base))
end
describe CarrierWave::ActiveRecord do
before(:all) { create_table("events") }
after(:all) { drop_table("events") }
before do
@uploader = Class.new(CarrierWave::Uploader::Base)
reset_class("Event")
@event = Event.new
end
after do
Event.delete_all
end
describe '#mount_uploader' do
before do
Event.mount_uploader(:image, @uploader)
end
describe '#image' do
it "should return blank uploader when nothing has been assigned" do
expect(@event.image).to be_blank
end
it "should return blank uploader when an empty string has been assigned" do
@event[:image] = ''
@event.save!
@event.reload
expect(@event.image).to be_blank
end
it "should retrieve a file from the storage if a value is stored in the database" do
@event[:image] = 'test.jpeg'
@event.save!
@event.reload
expect(@event.image).to be_an_instance_of(@uploader)
end
it "should set the path to the store dir" do
@event[:image] = 'test.jpeg'
@event.save!
@event.reload
expect(@event.image.current_path).to eq public_path('uploads/test.jpeg')
end
it "should return valid JSON when to_json is called when image is nil" do
expect(@event[:image]).to be_nil
hash = JSON.parse(@event.to_json)
expect(hash.keys).to include("image")
expect(hash["image"].keys).to include("url")
expect(hash["image"]["url"]).to be_nil
end
it "should return valid JSON when to_json is called when image is present" do
@event[:image] = 'test.jpeg'
@event.save!
@event.reload
expect(JSON.parse(@event.to_json)["image"]).to eq({"url" => "/uploads/test.jpeg"})
end
it "should return valid JSON when to_json is called on a collection containing uploader from a model" do
@event[:image] = 'test.jpeg'
@event.save!
@event.reload
expect(JSON.parse({:data => @event.image}.to_json)).to eq({"data"=>{"url"=>"/uploads/test.jpeg"}})
end
it "should return valid XML when to_xml is called when image is nil" do
hash = Hash.from_xml(@event.to_xml)["event"]
expect(@event[:image]).to be_nil
expect(hash.keys).to include("image")
expect(hash["image"].keys).to include("url")
expect(hash["image"]["url"]).to be_nil
end
it "should return valid XML when to_xml is called when image is present" do
@event[:image] = 'test.jpeg'
@event.save!
@event.reload
expect(Hash.from_xml(@event.to_xml)["event"]["image"]).to eq({"url" => "/uploads/test.jpeg"})
end
it "should respect options[:only] when passed to as_json for the serializable hash" do
@event[:image] = 'test.jpeg'
@event.save!
@event.reload
expect(@event.as_json(:only => [:foo])).to eq({"foo" => nil})
end
it "should respect options[:except] when passed to as_json for the serializable hash" do
@event[:image] = 'test.jpeg'
@event.save!
@event.reload
expect(@event.as_json(:except => [:id, :image, :images, :textfiles, :foo])).to eq({"textfile" => nil})
end
it "should respect both options[:only] and options[:except] when passed to as_json for the serializable hash" do
@event[:image] = 'test.jpeg'
@event.save!
@event.reload
expect(@event.as_json(:only => [:foo], :except => [:id])).to eq({"foo" => nil})
end
it "should respect options[:only] when passed to to_xml for the serializable hash" do
@event[:image] = 'test.jpeg'
@event.save!
@event.reload
expect(Hash.from_xml(@event.to_xml(only: [:foo]))["event"]["image"]).to be_nil
end
it "should respect options[:except] when passed to to_xml for the serializable hash" do
@event[:image] = 'test.jpeg'
@event.save!
@event.reload
expect(Hash.from_xml(@event.to_xml(except: [:image]))["event"]["image"]).to be_nil
end
it "should respect both options[:only] and options[:except] when passed to to_xml for the serializable hash" do
@event[:image] = 'test.jpeg'
@event.save!
@event.reload
expect(Hash.from_xml(@event.to_xml(only: [:foo], except: [:id]))["event"]["image"]).to be_nil
end
it "resets cached value on record reload" do
@event.image = CarrierWave::SanitizedFile.new(stub_file('new.jpeg', 'image/jpeg'))
@event.save!
expect(@event.reload.image).to be_present
Event.find(@event.id).update_column(:image, nil)
expect(@event.reload.image).to be_blank
end
context "with CarrierWave::MiniMagick" do
before(:each) do
@uploader.send(:include, CarrierWave::MiniMagick)
end
it "has width and height" do
@event.image = stub_file('landscape.jpg')
expect(@event.image.width).to eq 640
expect(@event.image.height).to eq 480
end
end
context "with CarrierWave::RMagick", :rmagick => true do
before(:each) do
@uploader.send(:include, CarrierWave::RMagick)
end
it "has width and height" do
@event.image = stub_file('landscape.jpg')
expect(@event.image.width).to eq 640
expect(@event.image.height).to eq 480
end
end
end
describe '#image=' do
it "should cache a file" do
@event.image = stub_file('test.jpeg')
expect(@event.image).to be_an_instance_of(@uploader)
end
it "should write nothing to the database, to prevent overriden filenames to fail because of unassigned attributes" do
expect(@event[:image]).to be_nil
end
it "should copy a file into the cache directory" do
@event.image = stub_file('test.jpeg')
expect(@event.image.current_path).to match(%r(^#{public_path('uploads/tmp')}))
end
context "when empty string is assigned" do
it "does nothing when" do
@event.image = ''
expect(@event.image).to be_blank
end
context "and the previous value was an empty string" do
before do
@event.image = ""
@event.save
end
it "does not write to dirty changes" do
@event.image = ''
expect(@event.changes.keys).not_to include("image")
end
end
end
context "when nil is assigned" do
it "does nothing" do
@event.image = nil
expect(@event.image).to be_blank
end
context "and the previous value was nil" do
before do
@event.image = nil
@event.save
end
it "does not write to dirty changes" do
@event.image = nil
expect(@event.changes.keys).not_to include("image")
end
end
end
context 'when validating allowlist integrity' do
before do
@uploader.class_eval do
def extension_allowlist
%w(txt)
end
end
end
it "should use I18n for integrity error messages" do
# Localize the error message to Dutch
change_locale_and_store_translations(:nl, :errors => {
:messages => {
:extension_allowlist_error => "Het opladen van %{extension} bestanden is niet toe gestaan. Geaccepteerde types: %{allowed_types}"
}
}) do
# Assigning image triggers check_allowlist! and thus should be inside change_locale_and_store_translations
@event.image = stub_file('test.jpg')
expect(@event).to_not be_valid
@event.valid?
expect(@event.errors[:image]).to eq (['Het opladen van "jpg" bestanden is niet toe gestaan. Geaccepteerde types: txt'])
end
end
end
context 'when validating denylist integrity' do
before do
@uploader.class_eval do
def extension_denylist
%w(jpg)
end
end
end
it "should use I18n for integrity error messages" do
# Localize the error message to Dutch
change_locale_and_store_translations(:nl, :errors => {
:messages => {
:extension_denylist_error => "You are not allowed to upload %{extension} files, prohibited types: %{prohibited_types}"
}
}) do
# Assigning image triggers check_denylist! and thus should be inside change_locale_and_store_translations
@event.image = stub_file('test.jpg')
expect(@event).to_not be_valid
@event.valid?
expect(@event.errors[:image]).to eq(['You are not allowed to upload "jpg" files, prohibited types: jpg'])
end
end
end
context 'when validating processing' do
before do
@uploader.class_eval do
process :monkey
def monkey
raise CarrierWave::ProcessingError
end
end
@event.image = stub_file('test.jpg')
end
it "should make the record invalid when a processing error occurs" do
expect(@event).to_not be_valid
end
it "should use I18n for processing errors without messages" do
@event.valid?
expect(@event.errors[:image]).to eq(['failed to be processed'])
change_locale_and_store_translations(:pt, :activerecord => {
:errors => {
:messages => {
:carrierwave_processing_error => 'falha ao processar imagem.'
}
}
}) do
expect(@event).to_not be_valid
expect(@event.errors[:image]).to eq(['falha ao processar imagem.'])
end
end
end
context 'when validating processing' do
before do
@uploader.class_eval do
process :monkey
def monkey
raise CarrierWave::ProcessingError, "Ohh noez!"
end
end
@event.image = stub_file('test.jpg')
end
it "should make the record invalid when a processing error occurs" do
expect(@event).to_not be_valid
end
it "should use the error's messages for processing errors with messages" do
@event.valid?
expect(@event.errors[:image]).to eq(['Ohh noez!'])
change_locale_and_store_translations(:pt, :activerecord => {
:errors => {
:messages => {
:carrierwave_processing_error => 'falha ao processar imagem.'
}
}
}) do
expect(@event).to_not be_valid
expect(@event.errors[:image]).to eq(['Ohh noez!'])
end
end
end
end
describe '#save' do
it "should do nothing when no file has been assigned" do
expect(@event.save).to be_truthy
expect(@event.image).to be_blank
end
it "should copy the file to the upload directory when a file has been assigned" do
@event.image = stub_file('test.jpeg')
expect(@event.save).to be_truthy
expect(@event.image).to be_an_instance_of(@uploader)
expect(@event.image.current_path).to eq public_path('uploads/test.jpeg')
end
it "should do nothing when a validation fails" do
Event.validate { |r| r.errors.add :textfile, "FAIL!" }
@event.image = stub_file('test.jpeg')
expect(@event.save).to be_falsey
expect(@event.image).to be_an_instance_of(@uploader)
expect(@event.image.current_path).to match(/^#{public_path('uploads/tmp')}/)
end
it "should assign the filename to the database" do
@event.image = stub_file('test.jpeg')
expect(@event.save).to be_truthy
@event.reload
expect(@event[:image]).to eq('test.jpeg')
expect(@event.image_identifier).to eq('test.jpeg')
end
it "should preserve the image when nothing is assigned" do
@event.image = stub_file('test.jpeg')
expect(@event.save).to be_truthy
@event = Event.find(@event.id)
@event.foo = "bar"
expect(@event.save).to be_truthy
expect(@event[:image]).to eq('test.jpeg')
expect(@event.image_identifier).to eq('test.jpeg')
end
it "should remove the image if remove_image? returns true" do
@event.image = stub_file('test.jpeg')
@event.save!
@event.remove_image = true
@event.save!
@event.reload
expect(@event.image).to be_blank
expect(@event[:image]).to eq(nil)
expect(@event.image_identifier).to eq(nil)
end
it "should mark image as changed when saving a new image" do
expect(@event.image_changed?).to be_falsey
@event.image = stub_file("test.jpeg")
expect(@event.image_changed?).to be_truthy
@event.save
@event.reload
expect(@event.image_changed?).to be_falsey
@event.image = stub_file("test.jpg")
expect(@event.image_changed?).to be_truthy
expect(@event.changed_for_autosave?).to be_truthy
end
end
describe "image?" do
it "returns true when the file is cached" do
@event.image = stub_file('test.jpg')
expect(@event.image?).to be_truthy
end
it "returns false when the file is removed" do
@event.remove_image!
@event.save!
expect(@event.image?).to be_falsey
end
it "returns true when the file is stored" do
@event.image = stub_file('test.jpg')
@event.save!
expect(@event.image?).to be_truthy
end
it "returns true when a file is removed and stored again" do
@event.image = stub_file('test.jpeg')
@event.save!
@event.remove_image!
@event.save!
@event.image = stub_file('test.jpeg')
@event.save!
expect(@event.image?).to be_truthy
end
end
describe "remove_image!" do
before do
@event.image = stub_file('test.jpeg')
@event.save!
end
it "should clear the serialization column" do
@event.remove_image!
expect(@event.attributes['image']).to be_blank
end
it "resets remove_image? to false" do
@event.remove_image = true
expect {
@event.remove_image!
}.to change {
@event.remove_image?
}.from(true).to(false)
end
end
describe "remove_image=" do
it "should mark the image as changed if changed" do
expect(@event.image_changed?).to be_falsey
expect(@event.remove_image).to be_nil
@event.remove_image = "1"
expect(@event.image_changed?).to be_truthy
end
end
describe "#remote_image_url=" do
before do
stub_request(:get, "http://www.example.com/test.jpg").to_return(body: File.read(file_path("test.jpg")))
end
# FIXME ideally image_changed? and remote_image_url_changed? would return true
it "should mark image as changed when setting remote_image_url" do
expect(@event.image_changed?).to be_falsey
@event.remote_image_url = 'http://www.example.com/test.jpg'
expect(@event.image_changed?).to be_truthy
@event.save!
@event.reload
expect(@event.image_changed?).to be_falsey
end
context 'when validating download' do
before do
@uploader.class_eval do
def download! file, headers = {}
raise CarrierWave::DownloadError
end
end
@event.remote_image_url = 'http://www.example.com/missing.jpg'
end
it "should make the record invalid when a download error occurs" do
expect(@event).to_not be_valid
end
it "should use I18n for download errors without messages" do
@event.valid?
expect(@event.errors[:image]).to eq(['could not be downloaded'])
change_locale_and_store_translations(:pt, :activerecord => {
:errors => {
:messages => {
:carrierwave_download_error => 'não pode ser descarregado'
}
}
}) do
expect(@event).to_not be_valid
expect(@event.errors[:image]).to eq(['não pode ser descarregado'])
end
end
end
end
describe '#destroy' do
it "should not raise an error with a custom filename" do
@uploader.class_eval do
def filename
"page.jpeg"
end
end
@event.image = stub_file('test.jpeg')
expect(@event.save).to be_truthy
expect {
@event.destroy
}.to_not raise_error
end
it "should do nothing when no file has been assigned" do
expect(@event.save).to be_truthy
@event.destroy
end
it "should remove the file from the filesystem" do
@event.image = stub_file('test.jpeg')
expect(@event.save).to be_truthy
expect(@event.image).to be_an_instance_of(@uploader)
expect(@event.image.current_path).to eq public_path('uploads/test.jpeg')
@event.destroy
expect(File.exist?(public_path('uploads/test.jpeg'))).to be_falsey
end
end
describe 'with overriddent filename' do
describe '#save' do
before do
@uploader.class_eval do
def filename
model.name + File.extname(super)
end
end
allow(@event).to receive(:name).and_return('jonas')
end
it "should copy the file to the upload directory when a file has been assigned" do
@event.image = stub_file('test.jpeg')
expect(@event.save).to be_truthy
expect(@event.image).to be_an_instance_of(@uploader)
expect(@event.image.current_path).to eq(public_path('uploads/jonas.jpeg'))
end
it "should assign an overridden filename to the database" do
@event.image = stub_file('test.jpeg')
expect(@event.save).to be_truthy
@event.reload
expect(@event[:image]).to eq('jonas.jpeg')
end
end
end
describe 'with validates_presence_of' do
before do
Event.validates_presence_of :image
allow(@event).to receive(:name).and_return('jonas')
end
it "should be valid if a file has been cached" do
@event.image = stub_file('test.jpeg')
expect(@event).to be_valid
end
it "should not be valid if a file has not been cached" do
expect(@event).to_not be_valid
end
end
describe 'with validates_size_of' do
before do
Event.validates_size_of :image, maximum: 40
allow(@event).to receive(:name).and_return('jonas')
end
it "should be valid if a file has been cached that matches the size criteria" do
@event.image = stub_file('test.jpeg')
expect(@event).to be_valid
end
it "should not be valid if a file has been cached that does not match the size criteria" do
@event.image = stub_file('bork.txt')
expect(@event).to_not be_valid
end
end
end
describe '#mount_uploader with mount_on' do
describe '#avatar=' do
it "should cache a file" do
reset_class("Event")
Event.mount_uploader(:avatar, @uploader, mount_on: :image)
@event = Event.new
@event.avatar = stub_file('test.jpeg')
@event.save
@event.reload
expect(@event.avatar).to be_an_instance_of(@uploader)
expect(@event.image).to eq('test.jpeg')
end
end
end
describe '#mount_uploader removing old files' do
before do
reset_class("Event")
Event.mount_uploader(:image, @uploader)
@event = Event.new
@event.image = stub_file('old.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
after do
FileUtils.rm_rf(public_path("uploads"))
end
describe 'normally' do
it "should remove old file if old file had a different path" do
@event.image = stub_file('new.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_falsey
end
it "should not remove old file if old file had a different path but config is false" do
@uploader.remove_previously_stored_files_after_update = false
@event.image = stub_file('new.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
it "should not remove file if old file had the same path" do
@event.image = stub_file('old.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
it "should not remove file if validations fail on save" do
Event.validate { |r| r.errors.add :textfile, "FAIL!" }
@event.image = stub_file('new.jpeg')
expect(@event.save).to be_falsey
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
it "should only delete the file once when the file is removed" do
@event.remove_image = true
expect_any_instance_of(CarrierWave::SanitizedFile).to receive(:delete).exactly(1).times
expect(@event.save).to be_truthy
end
end
describe 'with an overriden filename' do
before do
@uploader.class_eval do
def filename
model.foo + File.extname(super)
end
end
@event.image = stub_file('old.jpeg')
@event.foo = 'test'
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/test.jpeg'))).to be_truthy
expect(@event.image.read).to eq('this is stuff')
end
it "should not remove file if old file had the same dynamic path" do
@event.image = stub_file('test.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/test.jpeg'))).to be_truthy
end
it "should remove old file if old file had a different dynamic path" do
@event.foo = "new"
@event.image = stub_file('test.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/test.jpeg'))).to be_falsey
end
end
end
describe '#mount_uploader removing old files with versions' do
before do
@uploader.version :thumb
reset_class("Event")
Event.mount_uploader(:image, @uploader)
@event = Event.new
@event.image = stub_file('old.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/thumb_old.jpeg'))).to be_truthy
end
after do
FileUtils.rm_rf(public_path("uploads"))
end
it "should remove old file if old file had a different path" do
@event.image = stub_file('new.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/thumb_new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_falsey
expect(File.exist?(public_path('uploads/thumb_old.jpeg'))).to be_falsey
end
it "should not remove file if old file had the same path" do
@event.image = stub_file('old.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/thumb_old.jpeg'))).to be_truthy
end
it 'should not remove old file if transaction is rollback' do
Event.transaction do
@event.image = stub_file('new.jpeg')
@event.save
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
raise ActiveRecord::Rollback
end
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
end
describe "#mount_uploader into transaction" do
before do
@uploader.version :thumb
reset_class("Event")
Event.mount_uploader(:image, @uploader)
@event = Event.new
end
after do
FileUtils.rm_rf(public_path("uploads"))
end
it "should not store file during rollback" do
Event.transaction do
@event.image = stub_file('new.jpeg')
@event.save
raise ActiveRecord::Rollback
end
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_falsey
end
it "should not change file during rollback" do
@event.image = stub_file('old.jpeg')
@event.save
Event.transaction do
@event.image = stub_file('new.jpeg')
@event.save
raise ActiveRecord::Rollback
end
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_falsey
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
end
describe '#mount_uploader removing old files with multiple uploaders' do
before do
@uploader = Class.new(CarrierWave::Uploader::Base)
@uploader1 = Class.new(CarrierWave::Uploader::Base)
reset_class("Event")
Event.mount_uploader(:image, @uploader)
Event.mount_uploader(:textfile, @uploader1)
@event = Event.new
@event.image = stub_file('old.jpeg')
@event.textfile = stub_file('old.txt')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.txt'))).to be_truthy
end
after do
FileUtils.rm_rf(public_path("uploads"))
end
it "should remove old file1 and file2 if old file1 and file2 had a different paths" do
@event.image = stub_file('new.jpeg')
@event.textfile = stub_file('new.txt')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_falsey
expect(File.exist?(public_path('uploads/new.txt'))).to be_truthy
expect(File.exist?(public_path('uploads/old.txt'))).to be_falsey
end
it "should remove old file1 but not file2 if old file1 had a different path but old file2 has the same path" do
@event.image = stub_file('new.jpeg')
@event.textfile = stub_file('old.txt')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_falsey
expect(File.exist?(public_path('uploads/old.txt'))).to be_truthy
end
it "should not remove file1 or file2 if file1 and file2 have the same paths" do
@event.image = stub_file('old.jpeg')
@event.textfile = stub_file('old.txt')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.txt'))).to be_truthy
end
end
describe '#mount_uploader removing old files with with mount_on' do
before do
reset_class("Event")
Event.mount_uploader(:avatar, @uploader, mount_on: :image)
@event = Event.new
@event.avatar = stub_file('old.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
after do
FileUtils.rm_rf(public_path("uploads"))
end
it "should remove old file if old file had a different path" do
@event.avatar = stub_file('new.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_falsey
end
it "should not remove file if old file had the same path" do
@event.avatar = stub_file('old.jpeg')
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
end
describe '#mount_uploaders' do
before do
Event.mount_uploaders(:images, @uploader)
end
describe '#images' do
it "should return blank uploader when nothing has been assigned" do
expect(@event.images).to be_empty
end
it "should retrieve a file from the storage if a value is stored in the database" do
@event[:images] = ['test.jpeg']
@event.save!
@event.reload
expect(@event.images[0]).to be_an_instance_of(@uploader)
end
it "should set the path to the store dir" do
@event[:images] = ['test.jpeg']
@event.save!
@event.reload
expect(@event.images[0].current_path).to eq public_path('uploads/test.jpeg')
end
it "should return valid JSON when to_json is called when images is nil" do
expect(@event[:images]).to be_nil
hash = JSON.parse(@event.to_json)
expect(hash.keys).to include("images")
expect(hash["images"]).to be_empty
end
it "should return valid JSON when to_json is called when images is present" do
@event[:images] = ['test.jpeg', 'old.jpeg']
@event.save!
@event.reload
expect(JSON.parse(@event.to_json)["images"]).to eq([{"url" => "/uploads/test.jpeg"}, {"url" => "/uploads/old.jpeg"}])
end
it "should return valid JSON when to_json is called on a collection containing uploader from a model" do
@event[:images] = ['test.jpeg']
@event.save!
@event.reload
expect(JSON.parse({:data => @event.images}.to_json)).to eq({"data"=>[{"url"=>"/uploads/test.jpeg"}]})
end
it "should return valid XML when to_xml is called when images is nil" do
hash = Hash.from_xml(@event.to_xml)["event"]
expect(@event[:images]).to be_nil
expect(hash.keys).to include("images")
expect(hash["images"]).to be_empty
end
it "should return valid XML when to_xml is called when images is present" do
@event[:images] = ['test.jpeg']
@event.save!
@event.reload
expect(Hash.from_xml(@event.to_xml)["event"]["images"]).to eq([{"url" => "/uploads/test.jpeg"}])
end
it "should respect options[:only] when passed to as_json for the serializable hash" do
@event[:images] = ['test.jpeg']
@event.save!
@event.reload
expect(@event.as_json(:only => [:foo])).to eq({"foo" => nil})
end
it "should respect options[:except] when passed to as_json for the serializable hash" do
@event[:images] = ['test.jpeg']
@event.save!
@event.reload
expect(@event.as_json(:except => [:id, :image, :images, :textfile, :foo])).to eq({"textfiles" => nil})
end
it "should respect both options[:only] and options[:except] when passed to as_json for the serializable hash" do
@event[:images] = ['test.jpeg']
@event.save!
@event.reload
expect(@event.as_json(:only => [:foo], :except => [:id])).to eq({"foo" => nil})
end
it "should respect options[:only] when passed to to_xml for the serializable hash" do
@event[:images] = ['test.jpeg']
@event.save!
@event.reload
expect(Hash.from_xml(@event.to_xml(only: [:foo]))["event"]["images"]).to be_nil
end
it "should respect options[:except] when passed to to_xml for the serializable hash" do
@event[:images] = ['test.jpeg']
@event.save!
@event.reload
expect(Hash.from_xml(@event.to_xml(except: [:images]))["event"]["images"]).to be_nil
end
it "should respect both options[:only] and options[:except] when passed to to_xml for the serializable hash" do
@event[:images] = ['test.jpeg']
@event.save!
@event.reload
expect(Hash.from_xml(@event.to_xml(only: [:foo], except: [:id]))["event"]["images"]).to be_nil
end
end
describe '#images=' do
it "should cache a file" do
@event.images = [stub_file('test.jpeg')]
expect(@event.images[0]).to be_an_instance_of(@uploader)
end
it "should write nothing to the database, to prevent overriden filenames to fail because of unassigned attributes" do
expect(@event[:images]).to be_nil
end
it "should copy a file into into the cache directory" do
@event.images = [stub_file('test.jpeg')]
expect(@event.images[0].current_path).to match(%r(^#{public_path('uploads/tmp')}))
end
it "should do nothing when nil is assigned" do
@event.images = nil
expect(@event.images).to be_empty
end
it "should do nothing when an empty string is assigned" do
@event.images = ''
expect(@event.images).to be_empty
end
context 'when validating allowlist integrity' do
before do
@uploader.class_eval do
def extension_allowlist
%w(txt)
end
end
end
it "should use I18n for integrity error messages" do
# Localize the error message to Dutch
change_locale_and_store_translations(:nl, :errors => {
:messages => {
:extension_allowlist_error => "Het opladen van %{extension} bestanden is niet toe gestaan. Geaccepteerde types: %{allowed_types}"
}
}) do
# Assigning images triggers check_allowlist! and thus should be inside change_locale_and_store_translations
@event.images = [stub_file('test.jpg')]
expect(@event).to_not be_valid
@event.valid?
expect(@event.errors[:images]).to eq (['Het opladen van "jpg" bestanden is niet toe gestaan. Geaccepteerde types: txt'])
end
end
end
context 'when validating denylist integrity' do
before do
@uploader.class_eval do
def extension_denylist
%w(jpg)
end
end
end
it "should use I18n for integrity error messages" do
# Localize the error message to Dutch
change_locale_and_store_translations(:nl, :errors => {
:messages => {
:extension_denylist_error => "You are not allowed to upload %{extension} files, prohibited types: %{prohibited_types}"
}
}) do
# Assigning images triggers check_denylist! and thus should be inside change_locale_and_store_translations
@event.images = [stub_file('test.jpg')]
expect(@event).to_not be_valid
@event.valid?
expect(@event.errors[:images]).to eq(['You are not allowed to upload "jpg" files, prohibited types: jpg'])
end
end
end
context 'when validating processing' do
before do
@uploader.class_eval do
process :monkey
def monkey
raise CarrierWave::ProcessingError
end
end
@event.images = [stub_file('test.jpg')]
end
it "should make the record invalid when a processing error occurs" do
expect(@event).to_not be_valid
end
it "should use I18n for processing errors without messages" do
@event.valid?
expect(@event.errors[:images]).to eq(['failed to be processed'])
change_locale_and_store_translations(:pt, :activerecord => {
:errors => {
:messages => {
:carrierwave_processing_error => 'falha ao processar imagesm.'
}
}
}) do
expect(@event).to_not be_valid
expect(@event.errors[:images]).to eq(['falha ao processar imagesm.'])
end
end
end
context 'when validating processing' do
before do
@uploader.class_eval do
process :monkey
def monkey
raise CarrierWave::ProcessingError, "Ohh noez!"
end
end
@event.images = [stub_file('test.jpg')]
end
it "should make the record invalid when a processing error occurs" do
expect(@event).to_not be_valid
end
it "should use the error's messages for processing errors with messages" do
@event.valid?
expect(@event.errors[:images]).to eq(['Ohh noez!'])
change_locale_and_store_translations(:pt, :activerecord => {
:errors => {
:messages => {
:carrierwave_processing_error => 'falha ao processar imagesm.'
}
}
}) do
expect(@event).to_not be_valid
expect(@event.errors[:images]).to eq(['Ohh noez!'])
end
end
end
end
describe '#save' do
it "should do nothing when no file has been assigned" do
expect(@event.save).to be_truthy
expect(@event.images).to be_empty
end
it "should copy the file to the upload directory when a file has been assigned" do
@event.images = [stub_file('test.jpeg')]
expect(@event.save).to be_truthy
expect(@event.images[0]).to be_an_instance_of(@uploader)
expect(@event.images[0].current_path).to eq public_path('uploads/test.jpeg')
end
it "should do nothing when a validation fails" do
Event.validate { |r| r.errors.add :textfile, "FAIL!" }
@event.images = [stub_file('test.jpeg')]
expect(@event.save).to be_falsey
expect(@event.images[0]).to be_an_instance_of(@uploader)
expect(@event.images[0].current_path).to match(/^#{public_path('uploads/tmp')}/)
end
it "should assign the filename to the database" do
@event.images = [stub_file('test.jpeg')]
expect(@event.save).to be_truthy
@event.reload
expect(@event[:images]).to eq(['test.jpeg'])
expect(@event.images_identifiers[0]).to eq('test.jpeg')
end
it "should preserve the images when nothing is assigned" do
@event.images = [stub_file('test.jpeg')]
expect(@event.save).to be_truthy
@event = Event.find(@event.id)
@event.foo = "bar"
expect(@event.save).to be_truthy
expect(@event[:images]).to eq(['test.jpeg'])
expect(@event.images_identifiers[0]).to eq('test.jpeg')
end
it "should remove the images if remove_images? returns true" do
@event.images = [stub_file('test.jpeg')]
@event.save!
@event.remove_images = true
@event.save!
@event.reload
expect(@event.images).to be_empty
expect(@event[:images]).to eq(nil)
expect(@event.images_identifiers[0]).to eq(nil)
end
it "should mark images as changed when saving a new images" do
expect(@event.images_changed?).to be_falsey
@event.images = [stub_file("test.jpeg")]
expect(@event.images_changed?).to be_truthy
@event.save
@event.reload
expect(@event.images_changed?).to be_falsey
@event.images = [stub_file("test.jpg")]
expect(@event.images_changed?).to be_truthy
expect(@event.changed_for_autosave?).to be_truthy
end
end
describe "remove_images!" do
before do
@event.images = [stub_file('test.jpeg')]
@event.save!
@event.remove_images!
end
it "should clear the serialization column" do
expect(@event.attributes['images']).to be_blank
end
it "should return to false after being saved" do
@event.save!
expect(@event.remove_images).to eq(false)
expect(@event.remove_images?).to eq(false)
end
end
describe "remove_images=" do
it "should mark the images as changed if changed" do
expect(@event.images_changed?).to be_falsey
expect(@event.remove_images).to be_nil
@event.remove_images = "1"
expect(@event.images_changed?).to be_truthy
end
it "should not mark the images as changed if falsey value is assigned" do
@event.remove_images = "0"
expect(@event.images_changed?).to be_falsey
@event.remove_images = "false"
expect(@event.images_changed?).to be_falsey
end
end
describe "#remote_images_urls=" do
before do
stub_request(:get, "http://www.example.com/test.jpg").to_return(body: File.read(file_path("test.jpg")))
end
# FIXME ideally images_changed? and remote_images_urls_changed? would return true
it "should mark images as changed when setting remote_images_urls" do
expect(@event.images_changed?).to be_falsey
@event.remote_images_urls = ['http://www.example.com/test.jpg']
expect(@event.images_changed?).to be_truthy
@event.save!
@event.reload
expect(@event.images_changed?).to be_falsey
end
context 'when validating download' do
before do
@uploader.class_eval do
def download! file, headers = {}
raise CarrierWave::DownloadError
end
end
@event.remote_images_urls = ['http://www.example.com/missing.jpg']
end
it "should make the record invalid when a download error occurs" do
expect(@event).to_not be_valid
end
it "should use I18n for download errors without messages" do
@event.valid?
expect(@event.errors[:images]).to eq(['could not be downloaded'])
change_locale_and_store_translations(:pt, :activerecord => {
:errors => {
:messages => {
:carrierwave_download_error => 'não pode ser descarregado'
}
}
}) do
expect(@event).to_not be_valid
expect(@event.errors[:images]).to eq(['não pode ser descarregado'])
end
end
end
end
describe '#destroy' do
it "should not raise an error with a custom filename" do
@uploader.class_eval do
def filename
"page.jpeg"
end
end
@event.images = [stub_file('test.jpeg')]
expect(@event.save).to be_truthy
expect {
@event.destroy
}.to_not raise_error
end
it "should do nothing when no file has been assigned" do
expect(@event.save).to be_truthy
@event.destroy
end
it "should remove the file from the filesystem" do
@event.images = [stub_file('test.jpeg')]
expect(@event.save).to be_truthy
expect(@event.images[0]).to be_an_instance_of(@uploader)
expect(@event.images[0].current_path).to eq public_path('uploads/test.jpeg')
@event.destroy
expect(File.exist?(public_path('uploads/test.jpeg'))).to be_falsey
end
end
describe 'with overriddent filename' do
describe '#save' do
before do
@uploader.class_eval do
def filename
model.name + File.extname(super)
end
end
allow(@event).to receive(:name).and_return('jonas')
end
it "should copy the file to the upload directory when a file has been assigned" do
@event.images = [stub_file('test.jpeg')]
expect(@event.save).to be_truthy
expect(@event.images[0]).to be_an_instance_of(@uploader)
expect(@event.images[0].current_path).to eq(public_path('uploads/jonas.jpeg'))
end
it "should assign an overridden filename to the database" do
@event.images = [stub_file('test.jpeg')]
expect(@event.save).to be_truthy
@event.reload
expect(@event[:images]).to eq(['jonas.jpeg'])
end
end
end
describe 'with validates_presence_of' do
before do
Event.validates_presence_of :images
allow(@event).to receive(:name).and_return('jonas')
end
it "should be valid if a file has been cached" do
@event.images = [stub_file('test.jpeg')]
expect(@event).to be_valid
end
it "should not be valid if a file has not been cached" do
expect(@event).to_not be_valid
end
end
describe 'with validates_size_of' do
before do
Event.validates_size_of :images, maximum: 2
allow(@event).to receive(:name).and_return('jonas')
end
it "should be valid if at the number criteria are met" do
@event.images = [stub_file('test.jpeg'), stub_file('old.jpeg')]
expect(@event).to be_valid
end
it "should be invalid if size criteria are exceeded" do
@event.images = [stub_file('test.jpeg'), stub_file('old.jpeg'), stub_file('new.jpeg')]
expect(@event).to_not be_valid
end
end
end
describe '#mount_uploaders with mount_on' do
describe '#avatar=' do
it "should cache a file" do
reset_class("Event")
Event.mount_uploaders(:avatar, @uploader, mount_on: :images)
@event = Event.new
@event.avatar = [stub_file('test.jpeg')]
@event.save
@event.reload
expect(@event.avatar[0]).to be_an_instance_of(@uploader)
expect(@event.images).to eq(['test.jpeg'])
end
end
end
describe '#mount_uploaders removing old files' do
before do
Event.mount_uploaders(:images, @uploader)
@event.images = [stub_file('old.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
after do
FileUtils.rm_rf(public_path("uploads"))
end
describe 'normally' do
it "should remove old file if old file had a different path" do
@event.images = [stub_file('new.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_falsey
end
it "should not remove old file if old file had a different path but config is false" do
allow(@uploader).to receive(:remove_previously_stored_files_after_update).and_return(false)
@event.images = [stub_file('new.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
it "should not remove file if old file had the same path" do
@event.images = [stub_file('old.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
it "should not remove file if validations fail on save" do
Event.validate { |r| r.errors.add :textfile, "FAIL!" }
@event.images = [stub_file('new.jpeg')]
expect(@event.save).to be_falsey
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
end
describe 'with an overriden filename' do
before do
@uploader.class_eval do
def filename
model.foo + File.extname(super)
end
end
@event.images = [stub_file('old.jpeg')]
@event.foo = 'test'
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/test.jpeg'))).to be_truthy
expect(@event.images[0].read).to eq('this is stuff')
end
it "should not remove file if old file had the same dynamic path" do
@event.images = [stub_file('test.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/test.jpeg'))).to be_truthy
end
it "should remove old file if old file had a different dynamic path" do
@event.foo = "new"
@event.images = [stub_file('test.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/test.jpeg'))).to be_falsey
end
end
end
describe '#mount_uploaders removing old files with versions' do
before do
@uploader.version :thumb
Event.mount_uploaders(:images, @uploader)
@event.images = [stub_file('old.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/thumb_old.jpeg'))).to be_truthy
end
after do
FileUtils.rm_rf(public_path("uploads"))
end
it "should remove old file if old file had a different path" do
@event.images = [stub_file('new.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/thumb_new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_falsey
expect(File.exist?(public_path('uploads/thumb_old.jpeg'))).to be_falsey
end
it "should not remove file if old file had the same path" do
@event.images = [stub_file('old.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/thumb_old.jpeg'))).to be_truthy
end
end
describe '#mount_uploaders removing old files with multiple uploaders' do
before do
@uploader = Class.new(CarrierWave::Uploader::Base)
@uploader1 = Class.new(CarrierWave::Uploader::Base)
reset_class("Event")
Event.mount_uploaders(:images, @uploader)
Event.mount_uploaders(:textfiles, @uploader1)
@event = Event.new
@event.images = [stub_file('old.jpeg')]
@event.textfiles = [stub_file('old.txt')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.txt'))).to be_truthy
end
after do
FileUtils.rm_rf(public_path("uploads"))
end
it "should remove old file1 and file2 if old file1 and file2 had a different paths" do
@event.images = [stub_file('new.jpeg')]
@event.textfiles = [stub_file('new.txt')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_falsey
expect(File.exist?(public_path('uploads/new.txt'))).to be_truthy
expect(File.exist?(public_path('uploads/old.txt'))).to be_falsey
end
it "should remove old file1 but not file2 if old file1 had a different path but old file2 has the same path" do
@event.images = [stub_file('new.jpeg')]
@event.textfiles = [stub_file('old.txt')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_falsey
expect(File.exist?(public_path('uploads/old.txt'))).to be_truthy
end
it "should not remove file1 or file2 if file1 and file2 have the same paths" do
@event.images = [stub_file('old.jpeg')]
@event.textfiles = [stub_file('old.txt')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.txt'))).to be_truthy
end
end
describe '#mount_uploaders removing old files with mount_on' do
before do
Event.mount_uploaders(:avatar, @uploader, mount_on: :images)
@event = Event.new
@event.avatar = [stub_file('old.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
after do
FileUtils.rm_rf(public_path("uploads"))
end
it "should remove old file if old file had a different path" do
@event.avatar = [stub_file('new.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/new.jpeg'))).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_falsey
end
it "should not remove file if old file had the same path" do
@event.avatar = [stub_file('old.jpeg')]
expect(@event.save).to be_truthy
expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
end
it "should not raise ArgumentError when with_lock method is called" do
expect { @event.with_lock {} }.to_not raise_error
end
it "should not raise ArgumentError when with_lock method is called" do
expect { @event.with_lock {} }.to_not raise_error
end
end
describe '#reload' do
before do
Event.mount_uploader(:image, @uploader)
end
context 'when #reload is overriden in the model' do
before do
Event.class_eval do
def reload(*)
super
end
end
@event.save
@event.image
end
it "clears @_mounters" do
expect { @event.reload }.to change { @event.instance_variable_get(:@_mounters) }.to(nil)
end
end
end
describe "#dup" do
before do
Event.mount_uploader(:image, @uploader)
end
it "appropriately removes the model reference from the new models uploader" do
@event.save
new_event = @event.dup
expect(new_event.image.model).not_to eq @event
end
context 'when #initialize_dup is overriden in the model' do
before do
Event.class_eval do
def initialize_dup(*)
super
end
end
@event.image
end
it "clears @_mounters" do
expect(@event.dup.instance_variable_get(:@_mounters)).to be_blank
end
end
end
end
|
Kadenze/carrierwave
|
spec/uploader/download_spec.rb
|
require 'spec_helper'
describe CarrierWave::Uploader::Download do
let(:uploader_class) { Class.new(CarrierWave::Uploader::Base) }
let(:uploader) { uploader_class.new }
let(:cache_id) { '1369894322-345-1234-2255' }
let(:base_url) { "http://www.example.com" }
let(:url) { base_url + "/test.jpg" }
let(:test_file) { File.read(file_path(test_file_name)) }
let(:test_file_name) { "test.jpg" }
after { FileUtils.rm_rf(public_path) }
describe 'RemoteFile' do
context 'when skip_ssrf_protection is false' do
subject do
CarrierWave::Uploader::Download::RemoteFile.new(url, {}, skip_ssrf_protection: false)
end
before do
stub_request(:get, "http://www.example.com/#{test_file_name}")
.to_return(body: test_file, headers: {"Content-Type" => 'image/jpeg', "Vary" => 'Accept-Encoding'})
subject.read
end
it 'returns content type' do
expect(subject.content_type).to eq 'image/jpeg'
end
it 'returns header' do
expect(subject.headers['vary']).to eq 'Accept-Encoding'
end
it 'returns resolved URI' do
expect(subject.uri.to_s).to match %r{http://[^/]+/test.jpg}
end
end
context 'when skip_ssrf_protection is true' do
subject do
CarrierWave::Uploader::Download::RemoteFile.new(url, {}, skip_ssrf_protection: true)
end
before do
WebMock.stub_request(:get, "http://www.example.com/#{test_file_name}")
.to_return(body: test_file, headers: {"Content-Type" => 'image/jpeg', "Vary" => 'Accept-Encoding'})
subject.read
end
it 'returns content type' do
expect(subject.content_type).to eq 'image/jpeg'
end
it 'returns header' do
expect(subject.headers['vary']).to eq 'Accept-Encoding'
end
it 'returns URI' do
expect(subject.uri.to_s).to eq 'http://www.example.com/test.jpg'
end
end
end
describe '#download!' do
before do
allow(CarrierWave).to receive(:generate_cache_id).and_return(cache_id)
stub_request(:get, "http://www.example.com/#{test_file_name}")
.to_return(body: test_file, headers: {'content-type': 'image/jpeg'})
end
context "when a file was downloaded" do
before do
uploader.download!(url)
end
it "caches a file" do
expect(uploader.file).to be_an_instance_of(CarrierWave::SanitizedFile)
end
it "'s cached" do
expect(uploader).to be_cached
end
it "stores the cache name" do
expect(uploader.cache_name).to eq("#{cache_id}/#{test_file_name}")
end
it "sets the filename to the file's sanitized filename" do
expect(uploader.filename).to eq("#{test_file_name}")
end
it "moves it to the tmp dir" do
expect(uploader.file.path).to eq(public_path("uploads/tmp/#{cache_id}/#{test_file_name}"))
expect(uploader.file.exists?).to be_truthy
end
it "sets the url" do
expect(uploader.url).to eq("/uploads/tmp/#{cache_id}/#{test_file_name}")
end
it "sets the content type" do
expect(uploader.content_type).to eq("image/jpeg")
end
end
context "with directory permissions set" do
let(:permissions) { 0777 }
it "sets permissions" do
uploader_class.permissions = permissions
uploader.download!(url)
expect(uploader).to have_permissions(permissions)
end
it "sets directory permissions" do
uploader_class.directory_permissions = permissions
uploader.download!(url)
expect(uploader).to have_directory_permissions(permissions)
end
end
describe "custom downloader" do
let(:klass) do
Class.new(CarrierWave::Downloader::Base) {
def download(url, request_headers={})
end
}
end
before do
uploader.downloader = klass
end
it "is supported" do
expect_any_instance_of(klass).to receive(:download).with(url, {})
uploader.download!(url)
end
end
end
describe "#skip_ssrf_protection?" do
let(:uri) { 'http://localhost/test.jpg' }
before do
WebMock.stub_request(:get, uri).to_return(body: test_file)
allow(uploader).to receive(:skip_ssrf_protection?).and_return(true)
end
it "allows local request to be made" do
uploader.download!(uri)
expect(uploader.file.read).to eq 'this is stuff'
end
end
end
|
TakuyaHarayama/flat_report
|
app/models/project.rb
|
# == Schema Information
#
# Table name: projects
#
# id :integer not null, primary key
# team_id :integer not null
# client_name :string not null
# project_name :string not null
# status :integer default(0), not null
# description :text
# scheduled_time :integer
# actual_time :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_projects_on_team_id (team_id)
#
# Foreign Keys
#
# fk_rails_... (team_id => teams.id)
#
class Project < ApplicationRecord
belongs_to :team
has_many :post_details, dependent: :destroy
enum status: { draft: 0, sales: 10, review: 20, dev: 30, ops: 40, maintenance: 50, closed: 999 }
validates :client_name, presence: true
validates :project_name, presence: true
validates :status, presence: true
def name
client_name + ' / ' + project_name
end
def described_users
post_details.map{ |d| d.post.user }.uniq
end
end
|
TakuyaHarayama/flat_report
|
app/controllers/application_controller.rb
|
require "application_responder"
class ApplicationController < ActionController::Base
self.responder = ApplicationResponder
protect_from_forgery with: :exception
respond_to :html
layout :set_layout
before_action :authenticate_user!
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :load_color
# optional just for fun
helper_method :current_hit
def current_hit
hit = cookies['hit'].to_i
hit += 1
cookies['hit'] = hit
hit
end
def load_color
@color = %w(pink red purple deep-purple indigo blue light-blue cyan teal green light-green lime yellow amber orange deep-orange brown grey).sample
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:username, { team_attributes:[:name] }])
end
def set_layout
if user_signed_in?
"application"
else
devise_controller? ? "login" : "application"
end
end
end
|
TakuyaHarayama/flat_report
|
app/views/posts/show.json.jbuilder
|
<filename>app/views/posts/show.json.jbuilder
json.extract! @post, :id, :title, :body, :published, :created_at, :updated_at
|
TakuyaHarayama/flat_report
|
app/models/post_detail.rb
|
<gh_stars>0
# == Schema Information
#
# Table name: post_details
#
# id :integer not null, primary key
# post_id :integer not null
# project_id :integer not null
# spent_time :integer not null
# content :text not null
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_post_details_on_post_id (post_id)
# index_post_details_on_project_id (project_id)
#
# Foreign Keys
#
# fk_rails_... (post_id => posts.id)
# fk_rails_... (project_id => projects.id)
#
class PostDetail < ApplicationRecord
belongs_to :post, inverse_of: :post_details
belongs_to :project
validates :spent_time, presence: true
validates :content, presence: true
end
|
TakuyaHarayama/flat_report
|
app/views/team/projects/index.json.jbuilder
|
json.array!(@projects) do |project|
json.extract! post, :id, :client_name, :project_name, :status, :description, :scheduled_time, :actual_time, :created_at, :updated_at
json.url team_projects_url(project, format: :json)
end
|
TakuyaHarayama/flat_report
|
config/application.rb
|
<gh_stars>0
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
module FlatReport
class Application < Rails::Application
config.load_defaults 5.1
# Test unit
config.generators.system_tests = nil
# I18n
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]
config.i18n.default_locale = :en
config.i18n.available_locales = [:ja, :en]
# Time zone
config.time_zone = 'Tokyo'
config.active_record.default_timezone = :local
# Generators
config.generators do |g|
g.assets false
g.helper false
g.template_engine = :slim
g.test_framework :rspec, view_specs: false, routing_specs: false
end
# Load paths
config.autoload_paths += %W[#{config.root}/lib]
# Assets precompile
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)
end
end
|
TakuyaHarayama/flat_report
|
config/initializers/time_formats.rb
|
# Custome formats
Time::DATE_FORMATS[:ja] = "%Y年%m月%d日 %H時%M分"
Date::DATE_FORMATS[:ja] = "%Y年%m月d日"
|
TakuyaHarayama/flat_report
|
app/controllers/users_controller.rb
|
<reponame>TakuyaHarayama/flat_report
# NOTE: Defined 'members' by routes.rb
class UsersController < ApplicationController
before_action :set_user, only: :show
def index
@users = current_user.team.users
end
def show; end
def new
@user = current_user.team.users.new
end
def create
@user = current_user.team.users.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to member_path(@user), notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
private
def user_params
params.require(:user).permit(:username, :email, :password, :password_confirmation)
end
def set_user
@user = current_user.team.users.find(params[:id])
end
end
|
TakuyaHarayama/flat_report
|
db/seeds.rb
|
# Team
Team.destroy_all
Team.create!(
name: 'fake_name',
access_token: 'fake_access_token'
)
team = Team.first
# Post
Project.destroy_all
team.projects.create!(
client_name: 'fake_client',
project_name: 'fake_project',
status: 0,
description: 'fake_description',
scheduled_time: 100,
actual_time: 150
)
# User
User.destroy_all
team.users.create!(
email: '<EMAIL>',
password: 'password',
password_confirmation: 'password'
)
# Post
Post.destroy_all
user = User.first
user.posts.create!(
published_at: Date.current - 1.day,
unknown_content: 'fake_unknown_content',
impression_content: 'fake_impression_content',
status: 0,
stars_count: 0
)
user.posts.create!(
published_at: Date.current,
unknown_content: 'fake_unknown_content2',
impression_content: 'fake_impression_content2',
status: 0,
stars_count: 0
)
# PostDetail
post = Post.first
post.post_details.create!(
project_id: Project.first.id,
spent_time: 1,
content: 'fake_content'
)
post = Post.second
post.post_details.create!(
project_id: Project.first.id,
spent_time: 2,
content: 'fake_content2'
)
# Star
user = User.first
user.stars.create!(
post_id: user.posts.first.id
)
|
TakuyaHarayama/flat_report
|
app/controllers/me/posts_controller.rb
|
class Me::PostsController < ApplicationController
before_action :set_post, only: [:edit, :update, :destroy]
helper_method :current_post_hit
def index
@posts = current_user.posts
end
def edit
end
def update
respond_to do |format|
if @post.update(post_params)
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { render :show, status: :ok, location: @post }
else
format.html { render :edit }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
def destroy
@post.destroy
respond_to do |format|
format.html { redirect_to me_posts_url, notice: 'Post was successfully destroyed.' }
format.json { head :no_content }
end
end
# TODO: Move another
def current_post_hit
hit = cookies['post_hit'].to_i
hit += 1
cookies['post_hit'] = hit
hit
end
private
def set_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:published_at, :unknown_content, :impression_content, :status, post_details_attributes: [:id, :project_id, :spent_time, :content, :_destroy])
end
end
|
TakuyaHarayama/flat_report
|
app/models/star.rb
|
# == Schema Information
#
# Table name: stars
#
# id :integer not null, primary key
# post_id :integer not null
# user_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_stars_on_post_id (post_id)
# index_stars_on_post_id_and_user_id (post_id,user_id) UNIQUE
# index_stars_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (post_id => posts.id)
# fk_rails_... (user_id => users.id)
#
class Star < ApplicationRecord
belongs_to :post, counter_cache: true
belongs_to :user
validates :user, uniqueness: { scope: :post }
end
|
TakuyaHarayama/flat_report
|
db/migrate/20171022225901_create_projects.rb
|
class CreateProjects < ActiveRecord::Migration[5.1]
def change
create_table :projects do |t|
t.references :team, foreign_key: true, null: false
t.string :client_name, null: false
t.string :project_name, null: false
t.integer :status, default: 0, null: false
t.text :description
t.integer :scheduled_time
t.integer :actual_time
t.timestamps
end
end
end
|
TakuyaHarayama/flat_report
|
app/controllers/me/posts/stars_controller.rb
|
class Me::Posts::StarsController < ApplicationController
def index
@posts = current_user.starred_posts
.includes(:user)
end
end
|
TakuyaHarayama/flat_report
|
app/controllers/pages_controller.rb
|
<gh_stars>0
class PagesController < ApplicationController
skip_before_action :authenticate_user!
include HighVoltage::StaticPage
end
|
TakuyaHarayama/flat_report
|
app/controllers/users/posts_controller.rb
|
class Users::PostsController < ApplicationController
before_action :set_user
def index
@posts = @user.posts.order(created_at: :desc)
end
private
def set_user
@user = current_user.team.users.find(params[:member_id])
end
end
|
TakuyaHarayama/flat_report
|
app/controllers/mes_controller.rb
|
<filename>app/controllers/mes_controller.rb
class MesController < ApplicationController
before_action :set_me, only: [:show, :edit, :update]
def show
end
def edit
end
def update
respond_to do |format|
if @me.update(me_params)
format.html { redirect_to me_path, notice: 'Me was successfully updated.' }
format.json { render :show, status: :ok, location: @me }
else
format.html { render :edit }
format.json { render json: @me.errors, status: :unprocessable_entity }
end
end
end
private
def set_me
@me = current_user
end
def me_params
params.require(:user).permit(:username, :first_name, :last_name, :email)
end
end
|
TakuyaHarayama/flat_report
|
config/routes.rb
|
Rails.application.routes.draw do
# Devise routings
devise_for :users
# Authenticated root path
authenticated :user do
root :to => "dashboard#dashboard", :as => "user_authenticated_root"
end
resource :me, only: [:show, :edit, :update]
resource :team, only: [:show, :edit, :update]
namespace :team do
resources :projects
end
resources :members, only: [:index, :show, :new, :create], controller: :users do
resources :posts, only: :index, module: :users
end
resources :posts, only: [:show, :new, :create] do
resources :stars, only: :create, controller: 'posts/stars' do
delete :destroy, on: :collection
end
end
namespace :me do
namespace :posts do
resources :stars, only: :index
end
resources :posts, only: [:index, :edit, :update, :destroy]
end
# Unauthenticated routings
get "/*id",to: 'pages#show', as: :page, format: false, constraints: HighVoltage::Constraints::RootRoute
# Root path
root 'pages#home'
end
|
TakuyaHarayama/flat_report
|
app/views/teams/show.json.jbuilder
|
json.extract! @team, :id, :name, :access_token, :created_at, :updated_at
|
TakuyaHarayama/flat_report
|
config/initializers/materialize.rb
|
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
class_attr_index = html_tag.index('class="')
first_tag_end_index = html_tag.index('>')
if class_attr_index.nil? || class_attr_index > first_tag_end_index
html_tag.insert(first_tag_end_index, ' class="error"')
else
html_tag.insert(class_attr_index + 7, 'error ')
end
end
|
TakuyaHarayama/flat_report
|
config/initializers/high_voltage.rb
|
<gh_stars>0
HighVoltage.configure do |config|
config.routes = false
end
|
TakuyaHarayama/flat_report
|
app/views/team/projects/show.json.jbuilder
|
<filename>app/views/team/projects/show.json.jbuilder
json.extract! @project, :id, :client_name, :project_name, :status, :description, :scheduled_time, :actual_time, :created_at, :updated_at
|
TakuyaHarayama/flat_report
|
app/views/mes/show.json.jbuilder
|
<reponame>TakuyaHarayama/flat_report
json.extract! @me, :id, :username, :first_name, :last_name, :email, :created_at, :updated_at
|
TakuyaHarayama/flat_report
|
app/models/team.rb
|
# == Schema Information
#
# Table name: teams
#
# id :integer not null, primary key
# name :string not null
# access_token :string
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_teams_on_access_token (access_token) UNIQUE
# index_teams_on_name (name) UNIQUE
#
class Team < ApplicationRecord
has_many :projects
has_many :users
validates :name, presence: true, uniqueness: true
validates :access_token, uniqueness: true
before_validation :set_access_token
def posts
Post.includes(:user).where(user_id: users.ids)
end
def post_activities_rate
max = users.size * number_of_days_created
(posts.size.to_f / max * 100).round(1)
end
def most_starred_post
max = posts.maximum(:stars_count)
posts.find_by('stars_count >= ?', max)
end
private
def set_access_token
self.access_token = access_token.presence || SecureRandom.hex
end
def number_of_days_created
(Date.current - created_at.to_date).to_i
end
end
|
TakuyaHarayama/flat_report
|
app/models/user.rb
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# team_id :integer not null
# first_name :string
# last_name :string
# username :string default(""), not null
# email :string default(""), not null
# encrypted_password :string default(""), not null
# reset_password_token :string
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0), not null
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :inet
# last_sign_in_ip :inet
# confirmation_token :string
# confirmed_at :datetime
# confirmation_sent_at :datetime
# unconfirmed_email :string
# failed_attempts :integer default(0), not null
# unlock_token :string
# locked_at :datetime
# role :integer default(0)
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_users_on_email (email) UNIQUE
# index_users_on_reset_password_token (reset_password_token) UNIQUE
# index_users_on_team_id (team_id)
#
# Foreign Keys
#
# fk_rails_... (team_id => teams.id)
#
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts
has_many :stars
has_many :starred_posts, through: :stars, source: :post
belongs_to :team
accepts_nested_attributes_for :team
def today_post?
posts.exists?(created_at: Time.current.all_day)
end
def starred?(post)
stars.exists?(post: post)
end
end
|
TakuyaHarayama/flat_report
|
db/migrate/20171022225900_create_posts.rb
|
class CreatePosts < ActiveRecord::Migration[5.1]
def change
create_table :posts do |t|
t.references :user, foreign_key: true, null: false
t.datetime :published_at, null: false
t.text :unknown_content
t.text :impression_content
t.integer :status, default: 0, null: false
t.integer :stars_count, default: 0, null: false
t.timestamps null: false
end
end
end
|
TakuyaHarayama/flat_report
|
app/models/post.rb
|
<reponame>TakuyaHarayama/flat_report
# == Schema Information
#
# Table name: posts
#
# id :integer not null, primary key
# user_id :integer not null
# published_at :datetime not null
# unknown_content :text
# impression_content :text
# status :integer default("draft"), not null
# stars_count :integer default(0), not null
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_posts_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
class Post < ApplicationRecord
has_many :post_details, inverse_of: :post, dependent: :destroy
has_many :stars, dependent: :destroy
accepts_nested_attributes_for :post_details, allow_destroy: true, reject_if: :all_blank
belongs_to :user
enum status: %i[draft closed published]
validates :published_at, presence: true
validates :status, presence: true
validates :stars_count, presence: true
end
|
TakuyaHarayama/flat_report
|
app/controllers/dashboard_controller.rb
|
class DashboardController < ApplicationController
def dashboard
end
end
|
TakuyaHarayama/flat_report
|
app/controllers/teams_controller.rb
|
class TeamsController < ApplicationController
before_action :set_team, only: [:show, :edit, :update]
def show
end
def edit
end
def update
respond_to do |format|
if @team.update(team_params)
format.html { redirect_to team_path, notice: 'Team was successfully updated.' }
format.json { render :show, status: :ok, location: @team }
else
format.html { render :edit }
format.json { render json: @team.errors, status: :unprocessable_entity }
end
end
end
private
def set_team
@team = current_user.team
end
def team_params
params.require(:team).permit(:name, :access_token)
end
end
|
AMSTKO/expo
|
packages/expo-dev-menu/TargetValidator.rb
|
<reponame>AMSTKO/expo
# Overrides CocoaPods class to bypass module dependencies check.
# We want to add vendored reanimated but then expo-dev-menu needs to
# depend on react modules which don't have modular_headers set.
module Pod
class Installer
class Xcode
class TargetValidator
private
_original_verify_swift_pods_have_module_dependencies = instance_method(:verify_swift_pods_have_module_dependencies)
define_method(:verify_swift_pods_have_module_dependencies) do
# save dev-menu target but remove it from pod_targets variable used by orginal implementation
# see: https://github.com/CocoaPods/CocoaPods/blob/f120f9fabda8bc7bea9995700e358ea22dd71cfe/lib/cocoapods/installer/xcode/target_validator.rb#L129-L153
dev_menu_target = pod_targets.extract! { |target| target.name == "expo-dev-menu" }
# call orginal implementation
_original_verify_swift_pods_have_module_dependencies.bind(self).()
# restore orginal pod_targets for other checks
pod_targets.push(*dev_menu_target)
end
end
end # class UserProjectIntegrator
end # class Installer
end # module Pod
|
AMSTKO/expo
|
packages/expo-modules-autolinking/scripts/ios/autolinking_manager.rb
|
<filename>packages/expo-modules-autolinking/scripts/ios/autolinking_manager.rb<gh_stars>1-10
require_relative 'constants'
require_relative 'package'
# Require extensions to CocoaPods' classes
require_relative 'cocoapods/pod_target'
require_relative 'cocoapods/target_definition'
require_relative 'cocoapods/user_project_integrator'
module Expo
class AutolinkingManager
require 'colored2'
include Pod
public def initialize(podfile, target_definition, options)
@podfile = podfile
@target_definition = target_definition
@options = options
@packages = resolve()['modules'].map { |json_package| Package.new(json_package) }
end
public def use_expo_modules!
if has_packages?
return
end
global_flags = @options.fetch(:flags, {})
tests = @options.fetch(:tests, [])
project_directory = Pod::Config.instance.project_root
UI.section 'Using Expo modules' do
@packages.each { |package|
# The module can already be added to the target, in which case we can just skip it.
# This allows us to add a pod before `use_expo_modules` to provide custom flags.
if @target_definition.dependencies.any? { |dependency| dependency.name == package.pod_name }
UI.message '— ' << package.name.green << ' is already added to the target'.yellow
next
end
podspec_dir_path = Pathname.new(package.podspec_dir).relative_path_from(project_directory).to_path
pod_options = {
:path => podspec_dir_path,
:testspecs => tests.include?(package.name) ? ['Tests'] : []
}.merge(global_flags, package.flags)
# Install the pod.
@podfile.pod(package.pod_name, pod_options)
# TODO: Can remove this once we move all the interfaces into the core.
next if package.pod_name.end_with?('Interface')
UI.message "— #{package.name.green} (#{package.version})"
}
end
self
end
# Spawns `expo-module-autolinking generate-package-list` command.
public def generate_package_list(target_name, target_path)
Process.wait IO.popen(generate_package_list_command_args(target_path)).pid
end
# If there is any package to autolink.
public def has_packages?
@packages.empty?
end
# Filters only these packages that needs to be included in the generated modules provider.
public def packages_to_generate
@packages.select { |package| package.modules_class_names.any? }
end
# Returns the provider name which is also a name of the generated file
public def modules_provider_name
@options.fetch(:providerName, Constants::MODULES_PROVIDER_FILE_NAME)
end
# privates
private def resolve
json = []
IO.popen(resolve_command_args) do |data|
while line = data.gets
json << line
end
end
begin
JSON.parse(json.join())
rescue => error
raise "Couldn't parse JSON coming from `expo-modules-autolinking` command:\n#{error}"
end
end
private def node_command_args(command_name)
search_paths = @options.fetch(:searchPaths, @options.fetch(:modules_paths, nil))
ignore_paths = @options.fetch(:ignorePaths, nil)
exclude = @options.fetch(:exclude, [])
args = [
'node',
'--eval',
'require(\'expo-modules-autolinking\')(process.argv.slice(1))',
command_name,
'--platform',
'ios'
]
if !search_paths.nil? && !search_paths.empty?
args.concat(search_paths)
end
if !ignore_paths.nil? && !ignore_paths.empty?
args.concat(['--ignore-paths'], ignore_paths)
end
if !exclude.nil? && !exclude.empty?
args.concat(['--exclude'], exclude)
end
args
end
private def resolve_command_args
node_command_args('resolve').concat(['--json'])
end
private def generate_package_list_command_args(target_path)
node_command_args('generate-package-list').concat([
'--target',
target_path
])
end
end # class AutolinkingManager
end # module Expo
|
AMSTKO/expo
|
packages/expo-modules-autolinking/scripts/ios/cocoapods/pod_target.rb
|
<filename>packages/expo-modules-autolinking/scripts/ios/cocoapods/pod_target.rb
# Overrides CocoaPods `PodTarget` class to make the `ReactCommon` pod define a module
# and tell CocoaPods to generate a modulemap for it. This is needed for Swift/JSI integration
# until the upstream podspec add `DEFINES_MODULE => YES` to build settings.
# See: https://github.com/CocoaPods/CocoaPods/blob/master/lib/cocoapods/target/pod_target.rb
module Pod
class PodTarget
private
_original_defines_module = instance_method(:defines_module?)
public
# @return [Boolean] Whether the target defines a "module"
# (and thus will need a module map and umbrella header).
#
# @note Static library targets can temporarily opt in to this behavior by setting
# `DEFINES_MODULE = YES` in their specification's `pod_target_xcconfig`.
#
define_method(:defines_module?) do
# Call the original method
original_result = _original_defines_module.bind(self).()
# Make ReactCommon specs define a module. This is required for ExpoModulesCore
# to use `ReactCommon/turbomodule/core` subspec as a module, from Swift.
# It also needs to handle versioned pods in Expo Go, so we check if the pod name
# ends with `ReactCommon` instead of checking if they're equal.
if !original_result && name.end_with?('ReactCommon')
root_spec.consumer(platform).pod_target_xcconfig['DEFINES_MODULE'] = 'YES'
return @defines_module = true
end
# Return the original value if not applicable for hack.
return original_result
end
end
end
|
CrossRef/funder-reconciler
|
config.ru
|
<gh_stars>0
require './reconciler.rb'
run Sinatra::Application
|
CrossRef/funder-reconciler
|
funder-reconciler.rb
|
require 'bundler/setup'
require 'sinatra'
require 'json'
require 'open-uri'
set :bind, '0.0.0.0'
helpers do
def search_funders test_funder_name
uri ="http://api.crossref.org/funders?query=#{URI::encode(test_funder_name)}"
res = open(uri).read
return JSON.parse(res)
end
end
get '/heartbeat/?' , :provides => [:html, :json] do
status = {:status => "OK", :pid => "#{$$}", :ruby_version => "#{RUBY_VERSION}", :phusion => defined?(PhusionPassenger) ? true : false }
status.to_json
end
post '/reconcile/?' , :provides => [:html, :json] do
content_type :json
queries = JSON.parse params['queries']
return {}.to_json unless queries['q0'].has_key?('type')
results = {}
queries.each_pair do |key,q|
hits = search_funders(q['query'])
results[key]=Hash.new
results[key]['result'] = Array.new
score = 0;
type = {"id" => "/fundref/funder", "name" => "Funder"}
hits['message']['items'].each do |hit|
doi = "http://dx.doi.org/10.13039/#{hit['id']}"
entry = {"id" => doi, "name"=>hit["name"], "type" => [type], "score"=> score, "match" => "false", "uri" => doi}
results[key]['result'].push(entry)
score =+ 1
end
end
results.to_json
end
get '/reconcile/?' , :provides => [:html, :json] do
callback = params['callback']
default_types = [{"id"=>"/fundref/funder_name", "name"=>"Open Funder ID"}]
r = {"name" => "Open Funder Registry Reconciliation Service", "identifierSpace" => "http://openfunder.crossref.org/openfunder", "schemaSpace" => "http://openfunder.crossref.org/ns/type.object.id", "defaultTypes" => default_types}
content_type :js
p = JSON.pretty_generate(r)
"#{callback}(#{p})"
end
|
captproton/jim-weirich-rubymotion-intro
|
app/lib/layout.rb
|
<gh_stars>1-10
module Layout
def make_label(text)
label = UILabel.alloc.initWithFrame([[0, 0], [150, 30]])
label.font = UIFont.systemFontOfSize(20)
label.text = text
label.textColor = UIColor.darkGrayColor
label.backgroundColor = UIColor.clearColor
label
end
def make_button(title, action)
button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
button.frame = [[0, 0], [150, 44]]
button.setTitle(title, forState:UIControlStateNormal)
button.setTitleColor(UIColor.blackColor, forState:UIControlStateNormal)
button.backgroundColor = UIColor.clearColor
button.addTarget(self, action: action, forControlEvents:UIControlEventTouchUpInside)
button
end
class LayoutBuilder
def initialize(view, xmargin, ymargin)
@view = view
@xmargin = xmargin
@ymargin = ymargin
@current_y = @ymargin
end
def <<(subview)
height = subview.frame.size.height
subview.frame = [
[@xmargin, @current_y],
[@view.frame.size.width - 2*@xmargin, height]
]
@view.addSubview(subview)
@current_y += height
self
end
end
def layout(view, xmargin, ymargin)
layout_builder = LayoutBuilder.new(view, xmargin, ymargin)
yield(layout_builder)
end
end
|
captproton/jim-weirich-rubymotion-intro
|
app/hello_view_controller.rb
|
class HelloViewController < UIViewController
include Layout
def viewDidLoad
view.backgroundColor = UIColor.whiteColor
layout(view, 10, 10) do |lb|
@hello = make_label("Hello, World")
@pushme = make_button("Push me", "pushed")
@clear_counter = make_button("Clear", "clear_counter")
lb << @hello << @pushme << @clear_counter
end
def pushed
@counter ||= 0
@counter += 1
@hello.text = "Hello, World (#{@counter})"
end
def clear_counter
@counter = 0
@hello.text = "Hello, World"
end
end
end
|
melvinsembrano/lockie
|
test/lockie/strategies/jwt_test.rb
|
require 'test_helper'
require 'auth_test_helper'
class Lockie::Strategies::JwtTest < ActionDispatch::IntegrationTest
include Warden::Test::Helpers
include AuthTestHelper
setup do
Lockie.configure do |c|
c.jwt_secret = "jwt-secret"
c.model_name = "User"
end
end
teardown { Warden.test_reset! }
test "should authenticate" do
user = users(:one)
post "/json", headers: {'HTTP_AUTHORIZATION' => "Bearer #{ user.create_token }", 'CONTENT_TYPE' => 'application/json'}
assert_equal "200", response.code
end
test "should not authenticate with expired token" do
user = users(:one)
post "/json", headers: {'HTTP_AUTHORIZATION' => "Bearer #{ user.create_token(exp: 1.hour.ago.to_i) }", 'CONTENT_TYPE' => 'application/json'}
assert_equal "401", response.code
end
end
|
melvinsembrano/lockie
|
lib/lockie/strategies/failed.rb
|
module Lockie
module Strategies
class Failed < ::Warden::Strategies::Base
include Lockie::LogHelper
def valid?
true
end
def authenticate!
set_message 'Unauthorised'
fail!
end
end
end
end
Warden::Strategies.add(:failed, Lockie::Strategies::Failed)
|
melvinsembrano/lockie
|
lib/lockie.rb
|
<filename>lib/lockie.rb
require 'rails'
require 'warden'
require_relative "lockie/rails"
require_relative "lockie/log_helper"
require_relative "lockie/model_helper"
require_relative "lockie/controller_helper"
require_relative "lockie/strategies/email_password"
require_relative "lockie/strategies/jwt"
require_relative "lockie/strategies/failed"
module Lockie
autoload :FailureApp, 'lockie/failure_app'
class Configuration
attr_accessor :model_name
attr_accessor :unauthenticated_path
attr_accessor :default_strategies
attr_accessor :jwt_secret
attr_accessor :hash_algorithm
attr_accessor :serialize_session
attr_accessor :callback_url
attr_accessor :scopes
attr_accessor :serializer_to_session, :serializer_from_session
attr_accessor :session_timeout
def initialize
@model_name = "User"
@unauthenticated_path = "/login"
@default_strategies = [:email_password, :jwt]
@hash_algorithm = "HS256"
@serialize_session = true
@callback_url = true
@scopes = []
@serializer_to_session = nil
@serializer_from_session = nil
@session_timeout = 3.hours
end
end
class << self
def configure
yield config
end
def config
@config ||= Configuration.new
end
end
end
|
melvinsembrano/lockie
|
lib/lockie/model_helper.rb
|
require 'jwt'
module Lockie
module ModelHelper
extend ActiveSupport::Concern
def auth_object
@auth_object ||= Lockie.config.model_name.classify.constantize
end
included do
def create_token(payload = {})
payload = {
aud: 'lockie-app',
sub: id,
sub_type: self.class.name,
}.merge(payload)
JWT.encode(payload, Lockie.config.jwt_secret, Lockie.config.hash_algorithm)
end
end
class_methods do
def find_by_token(token)
payloads = decode_token token
find_auth payloads.first
end
def find_auth(payload)
auth_id = extract_auth_id payload
find auth_id
end
def extract_auth_id(payload)
payload.fetch('sub') { nil }
end
def decode_token(token, secret: Lockie::config.jwt_secret)
JWT.decode(token, secret, true, { algorithm: Lockie.config.hash_algorithm })
end
def create_token(payload: {}, secret: , hash_algorithm: 'HS256')
payload = {
aud: 'lockie-app',
}.merge(payload)
JWT.encode(payload, secret, hash_algorithm)
end
end
end
end
|
melvinsembrano/lockie
|
lib/lockie/strategies/jwt.rb
|
<gh_stars>1-10
module Lockie
module Strategies
class Jwt < ::Warden::Strategies::Base
include Lockie::ModelHelper
include Lockie::LogHelper
def auth
@auth ||= ActionDispatch::Request.new(env)
end
def headers
auth.headers
end
def valid?
headers['Authorization'].present?
end
def token
headers['Authorization'].split.last.strip
end
def authenticate!
begin
auth = auth_object.find_by_token(token)
if auth
success! auth
else
set_message "Invalid token"
fail!
end
rescue # => err
set_message "Invalid token"
fail!
end
end
end
end
end
Warden::Strategies.add(:jwt, Lockie::Strategies::Jwt)
|
melvinsembrano/lockie
|
lib/lockie/strategies/email_password.rb
|
module Lockie
module Strategies
class EmailPassword < ::Warden::Strategies::Base
include Lockie::ModelHelper
include Lockie::LogHelper
def request
@request ||= ActionDispatch::Request.new(env)
end
def valid?
request.params['email'].present? && request.params['password'].present?
end
def authenticate!
auth = auth_object.find_by_email(request.params['email'])
if auth && auth.authenticate(request.params['password'])
success!(auth)
else
set_message('Invalid username or password')
fail!
end
end
end
end
end
Warden::Strategies.add(:email_password, Lockie::Strategies::EmailPassword)
|
melvinsembrano/lockie
|
lib/lockie/failure_app.rb
|
<reponame>melvinsembrano/lockie
require 'action_controller/metal'
module Lockie
class FailureApp < ActionController::Metal
include ActionController::Redirecting
delegate :flash, to: :request
def self.call(*args)
req = ActionDispatch::Request.new(*args)
action(req.env['warden.options'][:action]).call(*args)
end
def unauthenticated
if request.xhr?
api_response(:text)
elsif request.format.to_sym == :json || request.content_type.to_s.split("/").last == 'json'
api_response(:json)
else
html_response
end
end
def api_response(format = :text)
self.status = 401
self.content_type = request.format.to_s
if format.eql?(:text)
self.response_body = message
else
self.response_body = { message: message }.to_json
end
end
def html_response
flash[type] = message if message
self.status = 302
if Lockie.config.callback_url
uri = URI(warden_options[:unauthenticated_path] || Lockie.config.unauthenticated_path)
# only add callback_url if original path is not the same with login path
unless request.original_fullpath == uri.path
callback_url = request.base_url + request.original_fullpath
uri.query = (uri.query.to_s.split("&") << "callback_url=#{ callback_url }").join("&")
end
redirect_to uri.to_s
else
redirect_to Lockie.config.unauthenticated_path
end
end
def message
@message ||= request.env['warden.message'] || "Unauthorized"
end
def warden_options
request.env['warden.options']
end
def type
@type ||= warden_options[:type] || :error
end
def warden
request.env['warden']
end
end
end
|
melvinsembrano/lockie
|
lib/lockie/rails.rb
|
require 'lockie/model_helper'
module Lockie
class Engine < ::Rails::Engine
config.app_middleware.use Warden::Manager do |manager|
manager.default_strategies Lockie.config.default_strategies
manager.failure_app = Lockie::FailureApp
if Lockie.config.serialize_session
serializer_to_session = Lockie.config.serializer_to_session || proc { |u| [u.class.name, u.id] }
manager.serialize_into_session(&serializer_to_session)
serializer_from_session = Lockie.config.serializer_from_session || proc { |s| s.first.constantize.find(s.last) }
manager.serialize_from_session(&serializer_from_session)
end
Lockie.config.scopes.each do |scope|
manager.scope_defaults(*scope)
end
end
end
end
Warden::Manager.after_authentication do |record, warden, options|
session_key = "warden.uls-#{record.class.name.underscore}-#{record.id}"
warden.request.session[session_key] = (Time.now + Lockie.config.session_timeout).to_s
end
Warden::Manager.after_set_user do |record, warden, options|
session_key = "warden.uls-#{record.class.name.underscore}-#{record.id}"
last_session_access = warden.request.session[session_key]
if last_session_access && Time.parse(last_session_access) < Time.now
# session expired
warden.logout
end
warden.request.session[session_key] = Time.now + Lockie.config.session_timeout
end
|
melvinsembrano/lockie
|
test/lockie/strategies/email_password_json_content_type_test.rb
|
<gh_stars>1-10
require 'test_helper'
require 'auth_test_helper'
class Lockie::Strategies::EmailPasswordJsonContentTypeTest < ActionDispatch::IntegrationTest
include Warden::Test::Helpers
include AuthTestHelper
setup do
Lockie.configure do |c|
c.model_name = "User"
end
end
teardown do
reset_lockie!
Warden.test_reset!
end
test "content should authenticate with email" do
user = users(:one)
post "/json", params: {
email: user.email,
password: '<PASSWORD>'
}.to_json,
headers: { "CONTENT_TYPE" => "application/json" }
assert_equal "200", response.code
end
test "content should not authenticate invalid password" do
user = users(:one)
post "/json", params: {
email: user.email,
password: '<PASSWORD>'
}.to_json,
headers: { "CONTENT_TYPE" => "application/json" }
body = JSON.parse(response.body)
assert_equal "401", response.code
assert_equal "Invalid username or password", body["message"]
end
end
|
melvinsembrano/lockie
|
test/auth_test_helper.rb
|
module AuthTestHelper
def app
Rack::Builder.new do
use Warden::Manager do |config|
config.failure_app = Lockie::FailureApp
config.default_strategies Lockie.config.default_strategies
end
map "/json" do
run lambda { |env|
env['warden'].authenticate
if env['warden'].user
[200, {'Content-Type' => 'text/json'}, ["OK,#{env['warden'].user.email}"]]
end
}
end
map "/xml" do
run lambda { |env|
env['warden'].authenticate
if env['warden'].user
[200, {'Content-Type' => 'text/xml'}, ['OK']]
end
}
end
map "/web" do
run lambda { |env|
env['warden'].authenticate
if env['warden'].user
[200, {'Content-Type' => 'text/html'}, ['OK']]
end
}
end
map "/hello" do
run lambda { |env|
if env['warden'].user
[200, {'Content-Type' => 'text/html'}, ['OK']]
end
}
end
end
end
end
|
melvinsembrano/lockie
|
test/dummy/app/models/user.rb
|
class User < ApplicationRecord
has_secure_password
include Lockie::ModelHelper
end
|
melvinsembrano/lockie
|
test/lockie/model_helper_test.rb
|
<reponame>melvinsembrano/lockie
require 'test_helper'
class Lockie::ControllerHelper::Test < ActiveSupport::TestCase
include Warden::Test::Helpers
class User
include Lockie::ModelHelper
def initialize(record)
@record = record
end
def id
@record.dig(:id)
end
def self.find(id)
{id: "1", name: "melvin"}
end
end
setup do
Lockie.configure do |c|
c.jwt_secret = "jwt-secret"
end
end
test "#create_token" do
user = User.new({})
assert user.respond_to?(:create_token)
end
test "#self.find_by_token" do
assert User.respond_to?(:find_by_token)
end
test "#self.find_by_token will return record" do
record = {id: "1", name: "melvin"}
token = User.new(record).create_token
assert_equal record, User.find_by_token(token)
end
test "#self.find_by_token should raise JWT::DecodeError" do
token = 'invalid token'
assert_raises(JWT::DecodeError) {
User.find_by_token(token)
}
end
test "#self.find_by_token should raise JWT::VerificationError" do
token = User.create_token(payload: {
sub_type: "System",
sub: "101",
}, secret: 'different-secret')
assert_raises(JWT::VerificationError) {
User.find_by_token(token)
}
end
test "#self.extract_auth_id" do
payload = {"aud"=>"lockie-app", "sub"=>"1", "sub_type"=>"User"}
assert_equal "1", User.extract_auth_id(payload)
end
test "#self.decode_token" do
token = User.create_token(payload: {
sub_type: "System",
sub: "101",
}, secret: 'i-am-secret')
payloads = User.decode_token token, secret: 'i-am-secret'
assert_equal "101", payloads.first.dig("sub")
assert_equal "System", payloads.first.dig("sub_type")
end
test "#self.decode_token should fail with invalid secret" do
token = User.create_token(payload: {
sub_type: "System",
sub: "101",
}, secret: 'i-am-secret')
assert_raises(JWT::VerificationError) {
User.decode_token token, secret: 'i-am-not-a-secret'
}
end
end
|
melvinsembrano/lockie
|
test/lockie_test.rb
|
require 'test_helper'
class Lockie::Test < ActiveSupport::TestCase
include Warden::Test::Helpers
teardown do
reset_lockie!
Warden.test_reset!
end
test "truth" do
assert_kind_of Module, Lockie
end
end
|
melvinsembrano/lockie
|
lib/lockie/log_helper.rb
|
module Lockie
module LogHelper
def set_message(message)
env['warden.message'] = message
end
end
end
|
melvinsembrano/lockie
|
test/lockie/controller_helper_test.rb
|
<filename>test/lockie/controller_helper_test.rb<gh_stars>1-10
require 'test_helper'
class Lockie::ControllerHelper::Test < ActiveSupport::TestCase
include Warden::Test::Helpers
teardown do
reset_lockie!
Warden.test_reset!
end
test "current auth helper should be #current_user" do
Lockie.configure do |c|
c.model_name = "User"
end
class UserAuthController
include Lockie::ControllerHelper
end
controller = UserAuthController.new
assert controller.respond_to?(:current_user)
end
test "current auth helper should be #current_account" do
Lockie.configure do |c|
c.model_name = "Account"
end
class AccountAuthController
include Lockie::ControllerHelper
end
controller = AccountAuthController.new
assert controller.respond_to?(:current_account)
end
test "current auth helper should be #current_mod_account" do
Lockie.configure do |c|
c.model_name = "Mod::Account"
end
class ModAccountAuthController
include Lockie::ControllerHelper
end
controller = ModAccountAuthController.new
assert controller.respond_to?(:current_mod_account)
end
# test "should serialize session properly with custom serializer" do
# Lockie.configure do |c|
# c.model_name = "User"
# c.serializer_to_session = proc { |u| u.id }
# c.serializer_from_session = proc { |id| User.find (id) }
# end
# class UserAuthController
# include Lockie::ControllerHelper
# end
# user = users(:one)
# login_as user
# controller = UserAuthController.new
# puts controller.current_user.inspect
# end
end
|
melvinsembrano/lockie
|
lib/lockie/controller_helper.rb
|
module Lockie
module ControllerHelper
extend ActiveSupport::Concern
included do
if respond_to?(:helper_method)
helper_method "current_#{ Lockie.config.model_name.underscore.gsub(/\//, '_') }".to_sym
helper_method :logged_in?
helper_method :authenticated?
end
def warden
return request.env['warden'] if defined?(request)
env['warden']
end
define_method "current_#{ Lockie.config.model_name.underscore.gsub(/\//, '_') }".to_sym do |*args|
warden.user(*args)
end
def authenticate!(scope = warden.config.default_scope)
warden.authenticate!({ scope: scope }.compact)
end
def authenticate(scope = warden.config.default_scope)
warden.authenticate({ scope: scope }.compact)
end
def authenticated?(*args)
warden.authenticated?(*args)
end
alias logged_in? authenticated?
def logout(*args)
authenticated?(args)
warden.logout
end
end
end
end
|
melvinsembrano/lockie
|
test/lockie/configuration_test.rb
|
require 'test_helper'
require 'auth_test_helper'
class Lockie::ConfigurationTest < ActionDispatch::IntegrationTest
include Warden::Test::Helpers
include AuthTestHelper
setup do
end
teardown do
reset_lockie!
Warden.test_reset!
end
test "should allow custom session serializer" do
Lockie.configure do |c|
c.model_name = "User"
c.serializer_to_session = proc {|u| u.id }
c.serializer_from_session = proc {|id| User.find(id) }
end
user = users(:one)
login_as user
get "/hello"
assert_equal "200", response.code
end
end
|
yellowhammer/secretary-rails
|
spec/internal/db/schema.rb
|
ActiveRecord::Schema.define do
create_table "animals", :force => true do |t|
t.string "name"
t.string "species"
t.string "color"
t.integer "person_id"
t.timestamps null: false
end
create_table "cars", :force => true do |t|
t.string "name"
t.string "color"
t.integer "year"
t.timestamps null: false
end
create_table "cars_locations", :force => true do |t|
t.integer "car_id"
t.integer "location_id"
end
create_table "hobbies", :force => true do |t|
t.string "title"
t.integer "person_id"
t.timestamps null: false
end
create_table "images", :force => true do |t|
t.string "title"
t.string "url"
t.integer "story_id"
t.timestamps null: false
end
create_table "locations", :force => true do |t|
t.string "title"
t.text "address"
t.timestamps null: false
end
create_table "people", :force => true do |t|
t.string "name"
t.string "ethnicity"
t.integer "age"
t.integer "location_id"
t.timestamps null: false
end
create_table "stories", :force => true do |t|
t.string "headline"
t.text "body"
t.timestamps null: false
end
create_table "story_users", :force => true do |t|
t.integer "story_id", null: false
t.integer "user_id", null: false
t.timestamps null: false
end
create_table "users", :force => true do |t|
t.string "name"
t.timestamps null: false
end
create_table "versions", :force => true do |t|
t.integer "version_number"
t.string "versioned_type"
t.integer "versioned_id"
t.integer "user_id"
t.text "description"
t.text "object_changes"
t.datetime "created_at"
end
end
|
yellowhammer/secretary-rails
|
spec/lib/secretary/versioned_attributes_spec.rb
|
<filename>spec/lib/secretary/versioned_attributes_spec.rb
require 'spec_helper'
describe Secretary::VersionedAttributes do
describe '::versioned_attributes' do
it 'uses the attributes set in the model' do
expect(Animal.versioned_attributes).to eq ["name", "color"]
end
it 'uses the column names minus the global ignores if nothing is set' do
expect(Location.versioned_attributes).to eq ["title", "address", "people"]
end
it 'subtracts unversioned attributes if they are set' do
expect(Person.versioned_attributes).not_to include "name"
expect(Person.versioned_attributes).not_to include "ethnicity"
end
end
describe '::versioned_attributes=' do
it 'sets the versioned attributes' do
original = Person.versioned_attributes
Person.versioned_attributes = ["name"]
expect(Person.versioned_attributes).to eq ["name"]
Person.versioned_attributes = original
end
it "raises ArgumentError if any of the attributes aren't strings" do
expect {
Person.versioned_attributes = [:a, :b, "c"]
}.to raise_error ArgumentError
end
end
describe '::unversioned_attributes=' do
it "removes the attributes from the versioned attributes" do
original = Person.versioned_attributes
Person.versioned_attributes = ["name", "ethnicity"]
Person.unversioned_attributes = ["name"]
expect(Person.versioned_attributes).to eq ["ethnicity"]
Person.versioned_attributes = original
end
it "raises ArgumentError if any of the attributes aren't strings" do
expect {
Person.unversioned_attributes = [:a, :b, "c"]
}.to raise_error ArgumentError
end
end
describe '#versioned_changes' do
let(:person) { create :person }
it 'is empty for non-dirty objects' do
expect(person.versioned_changes).to eq Hash[]
end
it "return a hash of changes for just the attributes we want" do
person.age = 120
person.name = "Freddie"
expect(person.versioned_changes).to eq Hash[{
"age" => [100, 120]
}]
end
end
describe '#versioned_attributes' do
let(:animal) { create :animal, :name => "Henry", :color => "henry" }
it 'is only the attributes we want' do
expect(animal.versioned_attributes).to eq Hash[{
"name" => "Henry",
"color" => "henry"
}]
end
end
describe '#versioned_attribute?' do
let(:person) { create :person }
it 'is true if the attribute should be versioned' do
expect(person.versioned_attribute?("age")).to eq true
expect(person.versioned_attribute?(:age)).to eq true
end
it 'is false if the attribute should not be versioned' do
expect(person.versioned_attribute?("name")).to eq false
expect(person.versioned_attribute?("id")).to eq false
end
end
end
|
yellowhammer/secretary-rails
|
lib/secretary/dirty_associations.rb
|
module Secretary
module DirtyAssociations
extend ActiveSupport::Concern
extend ActiveSupport::Autoload
autoload :Collection
autoload :Singular
COLLECTION_SUFFIX = "_were"
SINGULAR_SUFFIX = "_was"
module ClassMethods
# Backport of rails/rails#5383f22bb83adbd0e2e3f182f68196f1fb1433fa
# For 4.2.0 support.
if ActiveRecord::VERSION::STRING < "4.2.1"
def persistable_attribute_names
@persistable_attribute_names ||= connection
.schema_cache.columns_hash(table_name).keys
end
def reset_column_information
super
@persistable_attribute_names = nil
end
end
private
def define_dirty_association_methods(name, reflection)
suffix = reflection.collection? ? COLLECTION_SUFFIX : SINGULAR_SUFFIX
module_eval <<-EOE, __FILE__, __LINE__ + 1
def #{name}_changed?
!!attribute_changed?("#{name}")
end
def #{name}#{suffix}
attribute_was("#{name}")
end
def #{name}_change
attribute_change("#{name}")
end
private
def #{name}_will_change!
return if #{name}_changed?
# If this is a persisted object, fetch the object from the
# database and get its associated objects. Otherwise, just
# use self. We can't use `reload` here because it is a
# destructive method and will lose the associations.
record = self.persisted? ? self.class.find(id) : self
previous = record.#{name}
# Since this might be called on a collection or singular
# association, we need to force it into an array if possible.
if self.class.reflect_on_association(:#{name}).collection?
previous = previous.to_a
end
__compat_set_attribute_was("#{name}", previous)
end
# Rails < 4.2
def reset_#{name}!
reset_attribute!("#{name}")
end
# Rails 4.2+
def restore_#{name}!
restore_attribute!("#{name}")
end
EOE
end
def add_callback_methods(cb_name, reflection, new_methods)
# The callbacks may not be an Array, so we'll force them into one.
reflection.options[cb_name] = Array(reflection.options[cb_name])
reflection.options[cb_name] += new_methods
end
# Necessary for Rails < 4.1
# We need to force the callbacks into an array.
def redefine_callback(cb_name, name, reflection)
send("#{cb_name}_for_#{name}=",
Array(reflection.options[cb_name])
)
end
end
private
# For association_attributes=
# Should we conditionally include this method? I would like to,
# but if we're checking if this model accepts nested attributes
# for the association, then accepts_nested_attributes_for would
# have to be declared *before* tracks_association, which is too
# strict for my tastes.
def assign_to_or_mark_for_destruction(record, *args)
name = association_name(record)
if self.class.reflect_on_association(name).collection? &&
versioned_attribute?(name)
previous = changed_attributes[name]
# Assume it will change. It may not. We'll handle that scenario
# after the attributes have been assigned.
send("#{name}_will_change!")
super(record, *args)
reset_changes_if_unchanged(record, name, previous)
else
super(record, *args)
end
end
# Rails 4.2 adds "set_attribute_was" which must be used, so we'll
# check for it.
def __compat_set_attribute_was(name, previous)
if respond_to?(:set_attribute_was, true)
# Rails 4.2+
set_attribute_was(name, previous)
else
# Rails < 4.2
changed_attributes[name] = previous
end
end
def __compat_clear_attribute_changes(name)
if respond_to?(:clear_attribute_change, true)
# Rails 5.0+
# call directly
attributes_changed_by_setter.except!(name)
elsif respond_to?(:clear_attribute_changes, true)
# Rails 4.2+
clear_attribute_changes([name])
else
# Rails < 4.2
self.changed_attributes.delete(name)
end
end
# Backport of rails/rails#5383f22bb83adbd0e2e3f182f68196f1fb1433fa
# For 4.2.0 support.
if ActiveRecord::VERSION::STRING < "4.2.1"
def keys_for_partial_write
super & self.class.persistable_attribute_names
end
end
end
end
|
yellowhammer/secretary-rails
|
lib/secretary/config.rb
|
module Secretary
class Config
DEFAULTS = {
:user_class => "::User",
:ignored_attributes => ['id', 'created_at', 'updated_at']
}
attr_writer :user_class
def user_class
@user_class || DEFAULTS[:user_class]
end
attr_writer :ignored_attributes
def ignored_attributes
@ignored_attributes || DEFAULTS[:ignored_attributes]
end
end
end
|
yellowhammer/secretary-rails
|
spec/factories.rb
|
FactoryGirl.define do
factory :animal do
name "Fred"
species "Elephant"
color "gray"
end
factory :car do
name "Betsy"
color "white"
year 1984
end
factory :image do
title "Obama"
url "http://obama.com/obama.jpg"
end
factory :location do
title "Crawford Family Forum"
address "474 S. Raymond, Pasadena"
end
factory :person do
name "Bryan"
ethnicity "none"
age 100
end
factory :story do
headline "Cool Headline"
body "Lorem, etc."
end
factory :user do
name "<NAME>"
end
factory :version, :class => "Secretary::Version" do
versioned { |v| v.association :story }
user
end
end
|
yellowhammer/secretary-rails
|
app/models/secretary/version.rb
|
<reponame>yellowhammer/secretary-rails
module Secretary
class Version < ActiveRecord::Base
#monkey patch
self.table_name = "secretary_versions"
acts_as_paranoid
belongs_to :version_object_change, dependent: :destroy, inverse_of: :version
validates :versioned, presence: true
validates :version_object_change, presence: true, uniqueness: true
before_validation(on: :create) {
set_values
}
before_create do
set_version_number
end
##
serialize :object_changes
belongs_to :versioned, :polymorphic => true
belongs_to :user, :class_name => Secretary.config.user_class
validates_presence_of :versioned
before_create :increment_version_number
##monkey patch
def object_changes
version_object_change&.object_changes
end
def object_changes=(oc)
get_version_object_change.object_changes = oc
end
def get_version_object_change
self.version_object_change || self.build_version_object_change
end
private
def set_values
self.user_id ||= RequestStore.store[:current_user_id]
self.change_type ||= get_change_type
self.account_id ||= get_account_id
self.versioned_class_name = self.versioned.class.name
get_version_object_change
end
def set_version_number
latest_version = self.class.unscoped.where(versioned: versioned).order("version_number").last
self.version_number = latest_version.try(:version_number).to_i + 1
end
def get_change_type
action = description.to_s.downcase.split.first.to_s
case action
when "created", "destroyed"
action
when "changed"
"updated"
end
end
def get_account_id
if versioned.respond_to? :account_id
versioned.account_id
end
end
##
class << self
# Builds a new version for the passed-in object
# Passed-in object is a dirty object.
# Version will be saved when the object is saved.
#
# If you must generate a version manually, this
# method should be used instead of `Version.create`.
# I didn't want to override the public ActiveRecord
# API.
def generate(object)
changes = object.send(:__versioned_changes)
object.versions.create({
:user_id => object.logged_user_id,
:description => generate_description(object, changes.keys),
:object_changes => changes
})
end
private
def generate_description(object, attributes)
changed_attributes = attributes.map(&:humanize).to_sentence
if was_created?(object)
"Created #{object.class.name.titleize} ##{object.id}"
elsif was_updated?(object)
"Changed #{changed_attributes}"
else
"Generated Version"
end
end
def was_created?(object)
object.persisted? && object.id_changed?
end
def was_updated?(object)
object.persisted? && !object.id_changed?
end
end
# The attribute diffs for this version
def attribute_diffs
@attribute_diffs ||= begin
changes = self.object_changes.dup
attribute_diffs = {}
# Compare each of object_b's attributes to object_a's attributes
# And if there is a difference, add it to the Diff
changes.each do |attribute, values|
# values is [previous_value, new_value]
diff = Diffy::Diff.new(values[0].to_s, values[1].to_s)
attribute_diffs[attribute] = diff
end
attribute_diffs
end
end
# A simple title for this version.
# Example: "Article #125 v6"
def title
"#{self.versioned.class.name.titleize} " \
"##{self.versioned.id} v#{self.version_number}"
end
private
def increment_version_number
latest_version = self.versioned.versions.order("version_number").last
self.version_number = latest_version.try(:version_number).to_i + 1
end
end
end
|
MnkGitBox/MNkAnimatedTabBarController
|
MNkAnimatedTabBarController.podspec
|
#
# Be sure to run `pod lib lint MNkAnimatedTabBarController.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'MNkAnimatedTabBarController'
s.version = '0.2.2.4'
s.summary = 'iOS Tab bar controller with animated button'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = 'Custom created tab bar controller with animated button.if you want to static button with no aniamtion you still can do it with this simple libbary. you have to do programatically way un till to developed story board version.'
s.homepage = 'https://github.com/MnkGitBox/MNkAnimatedTabBarController'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '<NAME>' => '<EMAIL>' }
s.source = { :git => 'https://github.com/MnkGitBox/MNkAnimatedTabBarController.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '11.0'
s.source_files = 'Classes/**/*'
s.swift_version = '4.0'
# s.resource_bundles = {
# 'MNkAnimatedTabBarController' => ['MNkAnimatedTabBarController/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
s.frameworks = 'UIKit'
s.dependency 'lottie-ios'
end
|
Mahyar1990/Pod-Chat-iOS-SDK
|
FanapPodChatSDK.podspec
|
<filename>FanapPodChatSDK.podspec
Pod::Spec.new do |s|
s.name = "FanapPodChatSDK"
s.version = "0.6.2.5"
s.summary = "Fanap's POD Chat SDK"
s.description = "This Package is used for creating chat apps for companies whoes want to use Fanap Chat Services; This Package will use Fanap-Pod-Async-SDK"
s.homepage = "https://github.com/Mahyar1990/Fanap-Chat-SDK"
s.license = "MIT"
s.author = { "Mahyar" => "<EMAIL>" }
s.platform = :ios, "10.0"
s.swift_versions = "4.0"
s.source = { :git => "https://github.com/Mahyar1990/Fanap-Chat-SDK.git", :tag => s.version }
s.source_files = "Pod-Chat-iOS-SDK/Chat/**/*.{h,swift,xcdatamodeld,m,momd}"
s.resources = "Pod-Chat-iOS-SDK/Chat/*.xcdatamodeld"
s.frameworks = "Foundation" , "CoreData" , "Contacts"
s.dependency "FanapPodAsyncSDK" , '~> 0.5.5'
s.dependency "Alamofire" , '~> 4.8.2'
end
|
carolgreene/trip-tracker
|
app/controllers/trips_controller.rb
|
<reponame>carolgreene/trip-tracker
require 'rack-flash'
class TripsController < ApplicationController
use Rack::Flash
get '/trips' do
if !logged_in?
flash[:message] = "You have to sign in to do that"
redirect '/login'
else
@user = User.find(session[:user_id])
erb :'/trips/trips'
end
end
get '/trips/new' do
if !logged_in?
flash[:message] = "You have to sign in to do that"
redirect '/login'
else
erb :'/trips/create_trip'
end
end
post '/trips' do
if !params[:trip_name].empty? && !params[:description].empty?
@trip = Trip.create(trip_name: params["trip_name"], description: params["description"])
@trip.user_id = session[:user_id]
@trip.save
flash[:message] = "New trip created"
erb :'/trips/trips'
else
flash[:message] = "All fields must be filled out"
redirect '/trips/new'
end
end
get '/trips/:id' do
@trip = Trip.find_by_id(params[:id])
if !logged_in?
flash[:message] = "You have to sign in to do that"
redirect '/login'
elsif current_user == @trip.user
erb :'/trips/show_trip'
else
flash[:message] = "You can only go to your own trips"
redirect '/trips'
end
end
get '/trips/:id/edit' do
@trip = Trip.find_by_id(params[:id])
if !logged_in?
flash[:message] = "You have to sign in to do that"
redirect '/login'
elsif current_user == @trip.user
erb :'trips/edit_trip'
else
flash[:message] = "You can only edit your own trips"
redirect '/trips'
end
end
patch '/trips/:id' do
@trip = Trip.find_by_id(params[:id])
if current_user != @trip.user
flash[:message] = "You can only edit your own trips"
redirect '/trips'
end
if params[:trip_name].empty? || params[:description].empty?
flash[:message] = "All fields need to be filled out"
redirect "/trips/#{@trip.id}/edit"
else
@trip.trip_name = params[:trip_name]
@trip.description = params[:description]
@trip.save
flash[:message] = "Edit complete"
redirect "/trips/#{@trip.id}"
end
end
delete '/trips/:id/delete' do
@trip = Trip.find_by_id(params[:id])
if !logged_in?
flash[:message] = "You have to sign in to do that"
redirect '/login'
elsif current_user == @trip.user
@trip.delete
flash[:message] = "Trip has been deleted"
redirect '/trips'
else
flash[:message] = "You can only delete your own trips"
redirect '/trips'
end
end
end
|
longbai/objc-netinfo
|
QNNetworkInfo.podspec
|
Pod::Spec.new do |s|
s.name = "QNNetworkInfo"
s.version = "0.0.1"
s.summary = "network infomation functions."
s.description = "Network infomation functions. Include dns servers, local ip, nettype"
s.homepage = 'https://github.com/qiniu/objc-netinfo'
s.author = 'Qiniu => <EMAIL>'
s.source = {:git => 'https://github.com/qiniu/objc-netinfo.git', :tag => "v#{s.version}"}
s.ios.deployment_target = '7.0'
s.osx.deployment_target = '10.8'
s.libraries = 'resolv'
s.ios.frameworks = 'SystemConfiguration', 'CoreTelephony'
s.source_files = 'NetworkInfo/**/*.{h,m}'
s.requires_arc = true
s.license = { :type => 'MIT', :text => <<-LICENSE
The MIT License (MIT)
Copyright (c) 2012-2016 qiniu.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
LICENSE
}
end
|
andrewmcodes/gem_actions
|
gem_actions.gemspec
|
<reponame>andrewmcodes/gem_actions
# frozen_string_literal: true
require_relative "lib/gem_actions/version"
Gem::Specification.new do |s|
s.name = "gem_actions"
s.version = GemActions::VERSION
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/andrewmcodes/gem_actions"
s.summary = "Examples of GitHub Actions for a Ruby gem"
s.description = "GitHub Action workflows for your Ruby gem"
s.metadata = {
"bug_tracker_uri" => "#{s.homepage}issues",
"changelog_uri" => "#{s.homepage}/blob/main/CHANGELOG.md",
"documentation_uri" => s.homepage,
"homepage_uri" => s.homepage,
"source_code_uri" => s.homepage
}
s.license = "MIT"
s.files = Dir.glob("lib/**/*") + Dir.glob("bin/**/*") + %w[README.md LICENSE.txt CHANGELOG.md]
s.require_paths = ["lib"]
s.required_ruby_version = ">= 2.5"
s.add_development_dependency "bundler", ">= 1.15"
s.add_development_dependency "rake", ">= 13.0"
s.add_development_dependency "rspec", "~> 3.9"
end
|
andrewmcodes/gem_actions
|
lib/gem_actions/version.rb
|
# frozen_string_literal: true
module GemActions # :nodoc:
VERSION = "0.0.2"
end
|
andrewmcodes/gem_actions
|
lib/gem_actions.rb
|
<filename>lib/gem_actions.rb
# frozen_string_literal: true
require "gem_actions/version"
|
totosimo/parentFriend
|
app/controllers/application_controller.rb
|
class ApplicationController < ActionController::Base
before_action :authenticate_user!
before_action :configure_permitted_parameters, if: :devise_controller?
include Pundit
after_action :verify_authorized, except: :index, unless: :skip_pundit?
after_action :verify_policy_scoped, only: :index, unless: :skip_pundit?
private
def default_url_options
{ host: ENV["DOMAIN"] || "localhost:3000" }
end
def after_sign_in_path_for(resource)
main_path
end
def skip_pundit?
devise_controller? || params[:controller] =~ /(^(rails_)?admin)|(^pages$)/
end
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name])
devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :bio, :date_of_birth, :photo])
end
end
|
totosimo/parentFriend
|
app/models/user.rb
|
<reponame>totosimo/parentFriend
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_one_attached :photo
reverse_geocoded_by :latitude, :longitude
after_validation :reverse_geocode, if: -> (user){ user.latitude.present? and user.latitude_changed? and user.longitude.present? and user.longitude_changed? }
has_many :user_chatrooms
has_many :bookings
has_many :chatrooms, through: :user_chatrooms
# validates :first_name, :last_name, presence: :true
end
|
totosimo/parentFriend
|
db/seeds.rb
|
<reponame>totosimo/parentFriend<filename>db/seeds.rb
require 'open-uri'
require 'faker'
require 'json'
starttime = Time.now
# Deleting ###############################################################
puts "Deleting all database entries..."
Booking.delete_all
Message.delete_all
Event.delete_all
UserChatroom.delete_all
Chatroom.delete_all
User.delete_all
puts "Done deleting. Starting seeding now."
puts
# Users ##################################################################
if Rails.env.production?
puts "Detected production environment."
usercount = 100
else
puts "Did not detect production environment."
usercount = 30
end
# Calls random user profile picture API and parses json response into
# an array of picture URLs
image_api_url = "https://randomuser.me/api/?results=#{usercount}&nat=de&inc=picture,name&noinfo"
api_response_json = open(image_api_url).read
api_response_parsed = JSON.parse(api_response_json)["results"]
def create_bios
bios = [
"Hi I am a happy parent of #{rand(1..6)}!",
"We love Berlin and the many #{["playgrounds", "skate parks", "outdoor activities"].sample} it offers, and we are looking forward to meeting #{["happy", "international", "easy going"].sample} people.",
"We are young parents in #{["Moabit", "Mitte", "Steglitz"].sample} and love #{["outdoor activities", "inline skates", "dancing"].sample}.",
"We are parents of #{rand(1..6)} and we love everything that has #{["skates", "wheels", "wings"].sample}.",
"I am a single parent new to #{["Pankow", "Schöneberg", "Kreuzberg"].sample} and would love to find some parent friends for our kids to play together and also have some #{["interesting conversations", "nice picnic", "fun at Berlin's public swimming pools"].sample} with other parents.",
"Our #{["twins", "triplets", "quadruplets"].sample} keep us busy exploring Berlin each day with them and we would love to meet other expat parents to go #{["on those adventures", "to the cinema", "for hiking"].sample} together.",
"Me and my spouse are both Le Wagon #{["fullstack developer", "data science", "mobile developer"].sample} alumni and we are seeking other devs to hang out and tech talk while our #{rand(1..6)} kids play in the playground."
]
return bios
end
email_suffix = 1
puts "Creating #{usercount} users..."
api_response_parsed.each do | hash_name_image |
bios_list = create_bios
user = User.new(
email: "<EMAIL>",
password: "<PASSWORD>",
first_name: hash_name_image["name"]["first"],
last_name: hash_name_image["name"]["last"],
bio: bios_list.sample,
date_of_birth: "#{rand(1966..1996)}-#{rand(1..12)}-#{rand(1..28)}",
latitude: "#{rand(52.434620..52.562476).round(6)}",
longitude: "#{rand(13.280831..13.572970).round(6)}"
)
# Save photos with Active Record to Cloudinary:
photo = URI.open(hash_name_image["picture"]["large"])
user.photo.attach(io: photo, filename: 'name.jpg', content_type: 'image/jpg')
user.save
User.last == "" ? (puts "Error!") : (puts "Added #{User.last.first_name} #{User.last.last_name}")
email_suffix += 1
end
puts "Finished creating users!"
puts
# Events #################################################################
event_list = [
[ "Picnic in Volkspark Wilmersdorf", "We will have a huge picnic basket with us with the basic stuff like bread, ham, cheese, plates, water, juices, etc. and we are looking for another family to join us.", "Eating", "2021-04-05 12:00:00", "2021-04-05 16:00:00", "Am Volkspark 53, 10715 Berlin", "https://cdn.pixabay.com/photo/2019/10/26/13/40/autumn-4579561_960_720.jpg" ],
[ "Skateboarding the bowls", "We will be skateboarding the amazing bowls at the Gleisdreieck Skatepark. Bring your boards and come join us!", "Sports","2021-03-15 16:00:00", "2021-03-15 18:00:00", "Möckernstraße 26, 10963 Berlin", "https://cdn.pixabay.com/photo/2019/02/04/17/18/skateboard-3975172_960_720.jpg" ],
[ "Pancake party at Kindercafe", "We are organizing a pancake party at Kindercafe 'Biene Maja'. We will bring all ingredients and the kids will make the pancakes with us!", "Eating", "2021-03-24 10:00:00", "2021-03-24 16:00:00", "Wilhelmstraße 1-6, 10961 Berlin", "https://images.unsplash.com/photo-1605959255155-832d05b77e6d?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80" ],
[ "Playground Landwehrkanal", "We will be playing all day long at the great playground at the Landwehrkanal in Kreuzberg. Bring enough water to drink and some sunscreen", "Playground","2021-04-15 10:00:00", "2021-04-15 17:00:00", "Carl-Herz-Ufer 5, 10961 Berlin", "https://images.unsplash.com/photo-1542868796-20f2ddc9d41f?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80" ],
[ "A day in the Zoo", "We are 4 families with 7 kids and will go to the zoo together, everyone is welcome to join us!", "Stroll", "2021-03-26 10:00:00", "2021-03-26 17:30:00", "Hardenbergplatz 8, 10787 Berlin", "https://images.unsplash.com/photo-1562805508-5b92dc24212d?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80" ],
[ "Sightseeing Brandenburg Gate", "We organize a sight seeing tour for our 10 year old and will hire a city guide to explain us everything. Come and join and we do the tour together and go for icecreams afterwards!", "Stroll", "2021-03-28 11:30:00", "2021-03-28 15:30:00", "Brandenburger Tor, 10117 Berlin", "https://cdn.pixabay.com/photo/2020/05/01/15/18/brand-front-of-the-brandenburg-gate-5117579_960_720.jpg" ],
[ "Playdate at Victoriapark", "We will gather and play in the sand to build some nice castles together", "Playground", "2021-03-23 12:00:00", "2021-03-23 17:00:00", "Viktoriapark, 10965 Berlin", "https://cdn.pixabay.com/photo/2017/07/28/09/34/sand-2548132_960_720.jpg" ],
[ "Visit <NAME>", "The market of Arminus is a very beautiful experience for our small ones with many things to see and learn. We will be 4 parents and 5 kids and anyone who wants to join us is very welcome.", "Stroll", "2021-04-01 12:00:00", "2021-04-01 14:00:00", "Arminiusstraße 2-4, 10551 Berlin", "https://cdn.pixabay.com/photo/2017/09/09/16/38/vegetables-2732589_960_720.jpg" ],
[ "Inline Skating Tempelhofer Feld", "Have you ever skated on an airfield?! This is your opportunity!", "Sports", "2021-04-09 11:00:00", "2021-04-09 16:30:00", "Tempelhofer Damm, 12101 Berlin", "https://cdn.pixabay.com/photo/2017/04/17/07/35/inline-skating-2236674_960_720.jpg" ],
[ "Feeding ducks at Spreebogen", "Getting some fresh air in our lungs and sun in our faces. Bring some old bread with you for feeding the ducks, it is a great fun for the kids :-)", "Stroll", "2021-04-03 11:00:00", "2021-04-03 13:00:00", "Alt-Moabit 103, 10559 Berlin", "https://cdn.pixabay.com/photo/2020/05/05/16/29/berlin-5133836_960_720.jpg" ],
[ "A great view over Berlin", "We have reserved a table for 10 in the restaurant on the top floor of the Fernsehturm and still have 5 seats left for others to join us", "Eating", "2021-04-08 12:00:00", "2021-04-08 13:30:00", "Panoramastraße 1A, 10178 Berlin", "https://cdn.pixabay.com/photo/2020/02/18/00/06/tv-tower-4858167_960_720.jpg" ],
[ "Birthday Party at 'Rosa Elefant'", "We will be celebrating the 4th birthday of our son Oscar at the cosy Kindercafé '<NAME>' in Kurfürstenstraße. Come and join our party!", "Eating","2021-04-11 10:00:00", "2021-04-11 13:00:00", "Kurfürstenstraße 57-60, 10785 Berlin", "https://images.unsplash.com/photo-1553803867-48ac36024cba?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1350&q=80" ]
]
user_id = 1
puts "Creating #{event_list.length} events..."
event_list.each do | name, description, event_type, date_time_start, date_time_end, address, event_image |
event = Event.create!(
name: name,
description: description,
event_type: event_type,
date_time_start: date_time_start,
date_time_end: date_time_end,
user: User.all.sample,
address: address
)
# Save photos with Active Record to Cloudinary:
photo = URI.open(event_image)
event.photo.attach(io: photo, filename: 'name.webp', content_type: 'image/webp')
event.save
Event.last == "" ? (puts "Error!") : (puts "Added #{Event.last.name}")
user_id += 1
end
puts "Finished creating events!"
puts
puts "Seed procedure completed in #{(Time.now - starttime).round(0)} seconds."
puts
# Chatrooms ###################################
# puts "Creating chatrooms..."
# Chatroom.create(name: 'Tom')
# Chatroom.create(name: 'Silvia')
# Chatroom.create(name: 'Sergey')
# Chatroom.create(name: 'Moabit is beste!')
# Chatroom.create(name: '<NAME> Treptow')
# puts "Finished!"
|
totosimo/parentFriend
|
app/controllers/pages_controller.rb
|
<gh_stars>0
class PagesController < ApplicationController
skip_before_action :authenticate_user!, only: [ :home ]
def home
end
def main
end
def meet
@users = User.near(current_user, 3)
@markersUsers = @users.geocoded.map do |user|
{
lat: user.latitude,
lng: user.longitude,
infoWindow: render_to_string(partial: "info_window_user", locals: { user: user }),
image_url: helpers.asset_url('user.webp')
}
end
end
def update_location
current_user.update(longitude: params[:longitude], latitude: params[:latitude])
render json: current_user.to_json(only: [:latitude, :longitude])
end
private
def location_params
params.permit(:latitude, :longitude)
end
end
|
totosimo/parentFriend
|
app/models/event.rb
|
<filename>app/models/event.rb<gh_stars>0
class Event < ApplicationRecord
belongs_to :user
geocoded_by :address
has_one_attached :photo
has_many :bookings, dependent: :destroy
after_validation :geocode, if: :will_save_change_to_address?
validates :name, :date_time_start, :date_time_end, :address, presence: :true
end
|
totosimo/parentFriend
|
db/migrate/20210303102923_create_events.rb
|
<filename>db/migrate/20210303102923_create_events.rb
class CreateEvents < ActiveRecord::Migration[6.0]
def change
create_table :events do |t|
t.string :name
t.text :description
t.float :latitude
t.float :longitude
t.datetime :date_time_start
t.datetime :date_time_end
t.references :user, null: false, foreign_key: true
t.timestamps
end
end
end
|
totosimo/parentFriend
|
app/channels/chatroom_channel.rb
|
class ChatroomChannel < ApplicationCable::Channel
def subscribed
# stream_from "some_channel"
chatroom = Chatroom.find(params[:id])
stream_for chatroom
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.