repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
AssociationPaupiette/paupiette
|
app/models/ambassadorship.rb
|
# == Schema Information
#
# Table name: ambassadorships
#
# id :bigint(8) not null, primary key
# user_id :integer
# city_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Ambassadorship < ApplicationRecord
belongs_to :user
belongs_to :city
end
|
AssociationPaupiette/paupiette
|
app/helpers/dashboard/advices_helper.rb
|
<reponame>AssociationPaupiette/paupiette<filename>app/helpers/dashboard/advices_helper.rb
module Dashboard::AdvicesHelper
end
|
AssociationPaupiette/paupiette
|
app/models/ability.rb
|
<gh_stars>0
class Ability
include CanCan::Ability
def initialize(user)
@user = user ||= User.new
guest
host if @user.host?
ambassador if @user.ambassador?
admin if @user.admin?
end
protected
def guest
can :manage, Message, from: @user
end
def host
can :manage, Meal, host: @user
end
def ambassador
can :manage, :city
can :verify, User, city_id: @user.managed_cities.pluck(:id)
end
def admin
can :manage, :all
end
end
|
AssociationPaupiette/paupiette
|
db/seeds.rb
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
cities = [
{name: 'Paris', active: true, latitude: 48.856614, longitude: 2.3522219000000177},
{name: 'Bordeaux', active: true, latitude: 44.84044, longitude: -0.5805},
{name: 'Quimper', active: true, latitude: 47.997542, longitude: -4.097898999999984},
{name: 'Marseille', active: false, latitude: 43.296482, longitude: 5.369779999999992},
{name: 'Lyon', active: false, latitude: 45.764043, longitude: 4.835658999999964},
{name: 'Toulouse', active: false, latitude: 43.604652, longitude: 1.4442090000000007},
{name: 'Nice', active: false, latitude: 43.7101728, longitude: 7.261953199999994},
{name: 'Nantes', active: false, latitude: 47.218371, longitude: -1.553621000000021},
{name: 'Strasbourg', active: false, latitude: 48.5734053, longitude: 7.752111300000024},
{name: 'Montpellier', active: false, latitude: 43.610769, longitude: 3.8767159999999876},
{name: 'Lille', active: false, latitude: 50.62925, longitude: 3.057256000000052},
{name: 'Rennes', active: false, latitude: 48.117266, longitude: -1.6777925999999752},
{name: 'Reims', active: false, latitude: 49.258329, longitude: 4.031696000000011},
{name: '<NAME>', active: false, latitude: 49.49437, longitude: 0.10792900000001282},
{name: '<NAME>', active: false, latitude: 45.439695, longitude: 4.387177899999983},
{name: 'Toulon', active: false, latitude: 43.124228, longitude: 5.927999999999997},
{name: 'Grenoble', active: false, latitude: 45.188529, longitude: 5.724523999999974},
{name: 'Dijon', active: false, latitude: 47.322047, longitude: 5.041479999999979},
{name: 'Angers', active: false, latitude: 47.47116159999999, longitude: -0.5518256999999949},
{name: 'Brest', active: false, latitude: 48.390394, longitude: -4.4860760000000255},
{name: '<NAME>', active: false, latitude: 48.00611000000001, longitude: 0.1995560000000296},
{name: 'Nîmes', active: false, latitude: 43.836699, longitude: 4.360053999999991},
{name: '<NAME>', active: false, latitude: 43.529742, longitude: 5.4474270000000615},
{name: '<NAME>', active: false, latitude: 45.77722199999999, longitude: 3.0870250000000397},
{name: 'Limoges', active: false, latitude: 45.83361900000001, longitude: 1.2611050000000432},
{name: 'Tours', active: false, latitude: 47.394144, longitude: 0.6848400000000083},
{name: 'Amiens', active: false, latitude: 49.894067, longitude: 2.2957529999999906},
{name: 'Villeurbanne', active: false, latitude: 45.771944, longitude: 4.89017089999993},
{name: 'Metz', active: false, latitude: 49.1193089, longitude: 6.1757155999999895},
{name: 'Nanterre', active: false, latitude: 48.892423, longitude: 2.215330999999992},
{name: 'Besançon', active: false, latitude: 47.237829, longitude: 6.024053900000013},
{name: 'Caen', active: false, latitude: 49.182863, longitude: -0.37067899999999554},
{name: 'Rouen', active: false, latitude: 49.44323199999999, longitude: 1.0999709999999823},
{name: 'Orléans', active: false, latitude: 47.902964, longitude: 1.9092510000000402},
{name: '<NAME>', active: false, latitude: 48.8396952, longitude: 2.2399123000000145},
{name: 'Nancy', active: false, latitude: 48.692054, longitude: 6.184416999999939},
{name: 'Montreuil', active: false, latitude: 48.863812, longitude: 2.4484509999999773},
]
cities.each do |city|
c = City.where(name: city[:name]).first_or_create
c.active = city[:active]
c.latitude = city[:latitude]
c.longitude = city[:longitude]
c.save
end
city_paris = City.where(name: 'Paris').first
city_bordeaux = City.where(name: 'Bordeaux').first
user_pa = User.where(first_name: 'Pierre-André', last_name: 'Boissinot', email: '<EMAIL>').first_or_initialize
unless user_pa.persisted?
user_pa.description = 'Description Pierre-André'
user_pa.admin = true
user_pa.password = '<PASSWORD>'
user_pa.password_confirmation = '<PASSWORD>'
user_pa.city = city_paris
user_pa.save
end
user_arnaud = User.where(first_name: 'Arnaud', last_name: 'Levy', email: '<EMAIL>').first_or_initialize
unless user_arnaud.persisted?
user_arnaud.description = 'Description Arnaud'
user_arnaud.admin = true
user_arnaud.password = '<PASSWORD>'
user_arnaud.password_confirmation = '<PASSWORD>'
user_arnaud.city = city_paris
user_arnaud.save
end
user_seb = User.where(first_name: 'Sébastien', last_name: 'Gaya', email: '<EMAIL>').first_or_initialize
unless user_seb.persisted?
user_seb.description = 'Description Sébastien'
user_seb.admin = true
user_seb.password = '<PASSWORD>'
user_seb.password_confirmation = '<PASSWORD>'
user_seb.city = city_bordeaux
user_seb.save
end
|
AssociationPaupiette/paupiette
|
app/controllers/pages_controller.rb
|
<filename>app/controllers/pages_controller.rb
class PagesController < ApplicationController
def index
@preregistration = Preregistration.new
@preregistration_cities = City.inactive
@map_center = { latitude: 46.71109, longitude: 1.7191036 }.to_json
@map_cities = City.active.map { |city|
{ latitude: city.latitude, longitude: city.longitude, url: city_hosts_path(city.slug) }
}.to_json
end
def press
add_breadcrumb t('menu.press')
end
def who
add_breadcrumb t('menu.who')
end
def legal
add_breadcrumb t('menu.legal')
end
end
|
AssociationPaupiette/paupiette
|
db/migrate/20181102084505_add_slugs_to_users_and_cities.rb
|
<gh_stars>0
class AddSlugsToUsersAndCities < ActiveRecord::Migration[5.2]
def change
add_column :cities, :slug, :string, default: '', null: false
add_column :users, :slug, :string, default: '', null: false
end
end
|
AssociationPaupiette/paupiette
|
db/migrate/20181113094109_rename_preregister_for_preregistration.rb
|
<filename>db/migrate/20181113094109_rename_preregister_for_preregistration.rb<gh_stars>0
class RenamePreregisterForPreregistration < ActiveRecord::Migration[5.2]
def change
rename_table :preregisters, :preregistrations
end
end
|
AssociationPaupiette/paupiette
|
db/migrate/20181031092714_change_profile_status_column_in_users.rb
|
<filename>db/migrate/20181031092714_change_profile_status_column_in_users.rb
class ChangeProfileStatusColumnInUsers < ActiveRecord::Migration[5.2]
def change
rename_column :users, :profile_status, :profile_verification
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/hosts_controller.rb
|
<filename>app/controllers/hosts_controller.rb
class HostsController < ApplicationController
respond_to :html, :js, only: [:index]
add_breadcrumb I18n.t('menu.hosts'), :hosts_path
def index
@cities = City.active
@users = User.hosts.approved.page params[:page]
@meals = Meal.opened
@map_center = { latitude: 46.8506542, longitude: 3.9984845 }.to_json
@users_active = @users.map { |user|
{ latitude: user.reduced_latitude, longitude: user.reduced_longitude, url: user_path(user_slug: user.slug) }
}.to_json
end
def city
@city = City.find_by slug: params[:city_slug]
@users = @city.hosts.approved.page params[:page]
@meals = @city.meals.opened
@map_center = { latitude: @city.latitude, longitude: @city.longitude }.to_json
@users_active = @users.map { |user|
{ latitude: user.reduced_latitude, longitude: user.reduced_longitude, url: user_path(user_slug: user.slug) }
}.to_json
add_breadcrumb @city
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/admin/preregistrations_controller.rb
|
<reponame>AssociationPaupiette/paupiette<gh_stars>0
class Admin::PreregistrationsController < Admin::ApplicationController
add_breadcrumb 'Préinscriptions', :admin_preregistrations_path
def index
@preregistrations = Preregistration.all
end
def import
Preregistration.import params[:csv]
redirect_to admin_preregistrations_path, notice: 'Données importées'
end
end
|
AssociationPaupiette/paupiette
|
test/models/user/review_test.rb
|
# == Schema Information
#
# Table name: user_reviews
#
# id :bigint(8) not null, primary key
# from_id :bigint(8)
# about_id :bigint(8)
# text :text
# approved :boolean default(FALSE)
# created_at :datetime not null
# updated_at :datetime not null
#
require 'test_helper'
class User::ReviewTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
AssociationPaupiette/paupiette
|
test/models/message_test.rb
|
<reponame>AssociationPaupiette/paupiette
# == Schema Information
#
# Table name: messages
#
# id :bigint(8) not null, primary key
# from_id :bigint(8)
# content :text
# read_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# conversation_id :integer
#
require 'test_helper'
class MessageTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
AssociationPaupiette/paupiette
|
test/controllers/ambassadorships_controller_test.rb
|
<gh_stars>0
require 'test_helper'
class AmbassadorshipsControllerTest < ActionDispatch::IntegrationTest
setup do
@ambassadorship = ambassadorships(:one)
end
test "should get index" do
get ambassadorships_url
assert_response :success
end
test "should get new" do
get new_ambassadorship_url
assert_response :success
end
test "should create ambassadorship" do
assert_difference('Ambassadorship.count') do
post ambassadorships_url, params: { ambassadorship: { } }
end
assert_redirected_to ambassadorship_url(Ambassadorship.last)
end
test "should show ambassadorship" do
get ambassadorship_url(@ambassadorship)
assert_response :success
end
test "should get edit" do
get edit_ambassadorship_url(@ambassadorship)
assert_response :success
end
test "should update ambassadorship" do
patch ambassadorship_url(@ambassadorship), params: { ambassadorship: { } }
assert_redirected_to ambassadorship_url(@ambassadorship)
end
test "should destroy ambassadorship" do
assert_difference('Ambassadorship.count', -1) do
delete ambassadorship_url(@ambassadorship)
end
assert_redirected_to ambassadorships_url
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/my/meals_controller.rb
|
class My::MealsController < My::ApplicationController
load_and_authorize_resource
add_breadcrumb I18n.t('my.meals.name'), :my_meals_path
def index
@meals = current_user.meals.future
end
def new
add_breadcrumb t('my.meals.new')
@meal = Meal.new capacity: 2, confirmed: 1, date: Date.tomorrow
end
def edit
add_breadcrumb t('my.meals.edit')
end
def create
@meal = Meal.new meal_params
if @meal.save
redirect_to :my_meals, notice: t('my.meals.saved')
else
render :new
end
end
def update
@meal.update meal_params
if @meal.save
redirect_to :my_meals, notice: t('my.meals.saved')
else
add_breadcrumb 'Modifier'
render :edit
end
end
def destroy
@meal.destroy
redirect_to my_meals_path, notice: 'Repas annulé'
end
private
def meal_params
params.require(:meal)
.permit(:date, :capacity, :confirmed, :description, :formula)
.merge({host_id: current_user.id})
end
end
|
AssociationPaupiette/paupiette
|
app/models/conversation.rb
|
<reponame>AssociationPaupiette/paupiette
# == Schema Information
#
# Table name: conversations
#
# id :bigint(8) not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
#
class Conversation < ApplicationRecord
has_and_belongs_to_many :users
has_many :messages, dependent: :destroy
default_scope { order(updated_at: :desc) }
def self.between(user, other_user)
from_ids = user.conversations.pluck(:id)
to_ids = other_user.conversations.pluck(:id)
ids = from_ids & to_ids
find_by id: ids
end
def other(user)
users.where.not(id: user.id)
end
def messages_to(user)
messages.where.not(from: user)
end
def mark_as_read_by!(user)
messages.where.not(from_id: user.id).each do |message|
message.mark_as_read_by!(user)
end
end
end
|
AssociationPaupiette/paupiette
|
test/models/user_test.rb
|
# == Schema Information
#
# Table name: users
#
# id :bigint(8) not null, primary key
# email :string default(""), not null
# encrypted_password :string default(""), not null
# reset_password_token :string
# reset_password_sent_at :datetime
# remember_created_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# first_name :string
# description :text
# specialties :text
# reception_days :string
# city_id :bigint(8)
# last_name :string
# host :boolean default(FALSE)
# admin :boolean default(FALSE)
# slug :string default(""), not null
# active :boolean default(TRUE), not null
# approved :boolean default(FALSE)
# address :string
# zipcode :string
# city :string
#
require 'test_helper'
class UserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
AssociationPaupiette/paupiette
|
app/controllers/admin/users_controller.rb
|
<gh_stars>0
class Admin::UsersController < Admin::ApplicationController
load_and_authorize_resource
add_breadcrumb 'Utilisateurs', :admin_users_path
def index
@admins = User.admins
@ambassadors = User.ambassadors
@guests = User.guests
@hosts = User.hosts
end
def admins
add_breadcrumb 'Administrateurs'
@users = User.admins.page params[:page]
end
def ambassadors
add_breadcrumb 'Ambassadeurs'
@users = User.ambassadors.page params[:page]
end
def guests
add_breadcrumb 'Convives'
@users = User.guests.page params[:page]
end
def hosts
add_breadcrumb 'Hôtes'
@users = User.hosts.page params[:page]
end
def search
add_breadcrumb 'Recherche'
@users = User.search(params[:term])
end
def new
@user = User.new
add_breadcrumb 'Nouvel utilisateur'
end
def show
add_breadcrumb @user
end
def edit
add_breadcrumb @user, [:admin, @user]
add_breadcrumb 'Modifier'
end
def create
@user = User.new user_params
if @user.save
redirect_to [:admin, @user], notice: 'L\'utilisateur a été créé'
else
# FIXME password empty prevents from saving
add_breadcrumb 'Nouvel utilisateur'
render :new
end
end
def update
@user.update user_params
if @user.save
redirect_to [:admin, @user], notice: 'L\'utilisateur a été modifié'
else
add_breadcrumb 'Modifier'
render :edit
end
end
def destroy
@user.destroy
redirect_to admin_users_path
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :slug, :address, :zipcode, :city_id,
:host, :admin, :active, :approved, :profile_verification, :description, :photo, :specialties, :identity_card,
reception_days: [], managed_city_ids: [])
end
end
|
AssociationPaupiette/paupiette
|
lib/tasks/app.rake
|
<filename>lib/tasks/app.rake
namespace :app do
namespace :db do
desc 'Get database from Heroku'
task :production do
Bundler.with_clean_env do
sh 'heroku pg:backups capture --app associationpaupiette'
sh 'curl -o db/latest.dump `heroku pg:backups public-url --app associationpaupiette`'
sh 'DISABLE_DATABASE_ENVIRONMENT_CHECK=1 bundle exec rails db:drop'
sh 'bundle exec rails db:create'
begin
sh 'pg_restore --verbose --clean --no-acl --no-owner -h localhost -U postgres -d paupiette_development db/latest.dump'
rescue
'There were some warnings or errors while restoring'
end
end
end
end
end
|
AssociationPaupiette/paupiette
|
app/mailers/message_mailer.rb
|
class MessageMailer < ApplicationMailer
def notification_email
@from = params[:from]
@to = params[:to]
@url = my_conversation_url(user_slug: @from.slug)
mail to: @to.email, subject: 'Vous avez un message'
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/my/reviews_controller.rb
|
class My::ReviewsController < My::ApplicationController
add_breadcrumb I18n.t('my.reviews.name')
def index
@conversations = current_user.conversations
end
def save
@user = User.find_by(slug: params[:user_slug])
@review = current_user.review_about(@user)
@review.text = params[:user_review][:text]
@review.approved = false
@review.save
redirect_to my_reviews_path, notice: t('my.reviews.saved')
end
end
|
AssociationPaupiette/paupiette
|
db/migrate/20181102162019_create_conversations.rb
|
<reponame>AssociationPaupiette/paupiette
class CreateConversations < ActiveRecord::Migration[5.2]
def change
create_table :conversations do |t|
t.timestamps
end
create_join_table :conversations, :users
remove_column :messages, :meal_id
remove_column :messages, :to_id
add_column :messages, :conversation_id, :integer, index: true, foreign_key: true
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/admin/dashboard_controller.rb
|
<gh_stars>0
class Admin::DashboardController < Admin::ApplicationController
def index
authorize! :read, :Dashboard
@active_cities = City.active
@inactive_cities = City.inactive
end
end
|
AssociationPaupiette/paupiette
|
test/models/meal_test.rb
|
# == Schema Information
#
# Table name: meals
#
# id :bigint(8) not null, primary key
# date :datetime
# host_id :bigint(8)
# capacity :integer
# created_at :datetime not null
# updated_at :datetime not null
# confirmed :integer default(1)
# remaining :integer
# description :text
# formula :integer
#
require 'test_helper'
class MealTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
AssociationPaupiette/paupiette
|
db/migrate/20181025121149_add_infos_to_users.rb
|
class AddInfosToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :first_name, :string
add_column :users, :description, :text
add_column :users, :specialties, :text
add_column :users, :reception_days, :string
add_column :users, :profile_status, :integer, default: 0
add_column :users, :role, :integer, default: 0
end
end
|
AssociationPaupiette/paupiette
|
test/system/meals_test.rb
|
<gh_stars>0
require "application_system_test_case"
class MealsTest < ApplicationSystemTestCase
setup do
@meal = meals(:one)
end
test "visiting the index" do
visit meals_url
assert_selector "h1", text: "Meals"
end
test "creating a Meal" do
visit meals_url
click_on "New Meal"
fill_in "Capacity", with: @meal.capacity
fill_in "Date", with: @meal.date
fill_in "Host", with: @meal.host_id
click_on "Create Meal"
assert_text "Meal was successfully created"
click_on "Back"
end
test "updating a Meal" do
visit meals_url
click_on "Edit", match: :first
fill_in "Capacity", with: @meal.capacity
fill_in "Date", with: @meal.date
fill_in "Host", with: @meal.host_id
click_on "Update Meal"
assert_text "Meal was successfully updated"
click_on "Back"
end
test "destroying a Meal" do
visit meals_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Meal was successfully destroyed"
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/my_cities/application_controller.rb
|
<filename>app/controllers/my_cities/application_controller.rb
class MyCities::ApplicationController < ApplicationController
before_action :redirect_if_unauthorized
before_action :load_city
def index
@cities = current_user.managed_cities
render 'my_cities/index'
end
protected
def load_city
@city = City.find_by(slug: params[:city_slug])
add_breadcrumb I18n.t('my_cities.name'), :my_cities_root_path
add_breadcrumb @city unless @city.nil?
end
def redirect_if_unauthorized
redirect_to :root unless can? :manage, :city
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/concerns/devise_permitted_params.rb
|
<reponame>AssociationPaupiette/paupiette<filename>app/controllers/concerns/devise_permitted_params.rb
module DevisePermittedParams
extend ActiveSupport::Concern
included do
before_action :configure_devise_permitted_parameters, if: :devise_controller?
end
def configure_devise_permitted_parameters
edit_user_params = [:first_name, :last_name, :description, :city_id, :photo, :identity_card, :specialties, :reception_days => []]
if params[:action] == 'update'
devise_parameter_sanitizer.permit(:account_update, keys: edit_user_params)
elsif params[:action] == 'create'
devise_parameter_sanitizer.permit(:sign_up, keys: [:host])
end
end
end
|
AssociationPaupiette/paupiette
|
app/models/user/review.rb
|
# == Schema Information
#
# Table name: user_reviews
#
# id :bigint(8) not null, primary key
# from_id :bigint(8)
# about_id :bigint(8)
# text :text
# approved :boolean default(FALSE)
# created_at :datetime not null
# updated_at :datetime not null
#
class User::Review < ApplicationRecord
belongs_to :from, class_name: 'User'
belongs_to :about, class_name: 'User'
scope :approved, -> { where(approved: true) }
scope :unapproved, -> { where(approved: false) }
end
|
AssociationPaupiette/paupiette
|
db/migrate/20181120163937_create_user_reviews.rb
|
<reponame>AssociationPaupiette/paupiette
class CreateUserReviews < ActiveRecord::Migration[5.2]
def change
create_table :user_reviews do |t|
t.references :from, foreign_key: {to_table: :users}
t.references :about, foreign_key: {to_table: :users}
t.text :text
t.boolean :approved, default: false
t.timestamps
end
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/preregistrations_controller.rb
|
class PreregistrationsController < ApplicationController
def create
@preregistration = Preregistration.new preregistration_params
if @preregistration.save
flash[:notice] = 'Votre préinscription est enregistrée'
else
flash[:warning] = 'Problème: votre préinscription n\'a pas pu être enregistrée'
end
redirect_to root_path
end
private
def preregistration_params
params.require(:preregistration).permit(:first_name, :email, :city_id)
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/my_cities/reviews_controller.rb
|
<gh_stars>0
class MyCities::ReviewsController < MyCities::ApplicationController
def index
@reviews = @city.reviews.page params[:page]
add_breadcrumb t('my_cities.reviews.name')
end
def approval
@reviews = @city.reviews.unapproved.page params[:page]
add_breadcrumb t('my_cities.reviews.to_approve')
end
def approve
@review = User::Review.find params[:id]
@review.approved = true
@review.save
flash[:notice] = 'Avis approuvé'
redirect_to my_cities_reviews_approval_path(city_slug: params[:city_slug])
end
def unapprove
@review = User::Review.find params[:id]
@review.approved = false
@review.save
flash[:notice] = 'Avis désapprouvé'
redirect_to my_cities_reviews_path(city_slug: params[:city_slug])
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/my/messages_controller.rb
|
class My::MessagesController < My::ApplicationController
add_breadcrumb I18n.t('my.messages.name'), :my_messages_path
def index
@conversations = current_user.conversations
end
def user
@user = User.find_by(slug: params[:user_slug])
@conversation = Conversation.between(current_user, @user)
@conversation.mark_as_read_by!(current_user) unless @conversation.nil?
@message = Message.new(from: current_user)
add_breadcrumb @user
end
def create
@user = User.find_by(slug: params[:user_slug])
@conversation = Conversation.between(current_user, @user)
if @conversation.nil?
@conversation = Conversation.create
@conversation.users << current_user
@conversation.users << @user
end
@message = Message.new(message_params)
@message.conversation = @conversation
if @message.save
redirect_to my_conversation_path(user_slug: @user.slug), notice: 'Message bien envoyé.'
else
redirect_to my_conversation_path(user_slug: @user.slug), notice: 'Erreur lors de l\'envoi du message'
end
end
private
def message_params
params.require(:message).permit(:from_id, :content)
end
end
|
AssociationPaupiette/paupiette
|
app/helpers/dashboard/messages_helper.rb
|
<gh_stars>0
module Dashboard::MessagesHelper
end
|
AssociationPaupiette/paupiette
|
db/migrate/20181123104922_refactor_meals.rb
|
<filename>db/migrate/20181123104922_refactor_meals.rb
class RefactorMeals < ActiveRecord::Migration[5.2]
def change
add_column :meals, :confirmed, :integer, default: 1
add_column :meals, :remaining, :integer
end
end
|
AssociationPaupiette/paupiette
|
lib/tasks/legacy.rake
|
require 'csv'
class Cities
LIST = ['Paris','Bordeaux','Quimper','Marseille','Lyon','Toulouse','Nice','Nantes','Strasbourg','Montpellier','Lille','Rennes','Reims', 'Le Havre''Saint Étienne','Toulon','Grenoble','Dijon','Angers','Brest','Le Mans','Nîmes','Aix en Provence','<NAME>','Limoges','Tours','Amiens','Villeurbanne','Metz','Nanterre','Besançon','Caen','Rouen','Orléans','<NAME>','Nancy','Montreuil']
def self.find(name)
LIST.each do |city|
if city.downcase.in? name.to_s.downcase
puts "#{name} -> #{city}"
return city
end
end
puts "#{name} -> not found"
return ''
end
end
namespace :legacy do
task :extract_preregistrations do
preregistrations = {}
preregistrations_launchrock = CSV.read './tmp/legacy/preregistrations_launchrock.csv'
preregistrations_launchrock.each_with_index do |row, index|
next if index.zero?
values = row.first.split ';'
email = values[1]
city = Cities.find values[3]
preregistrations[email] = {
email: email,
first_name: '',
city: city
}
end
preregistrations_form = CSV.read './tmp/legacy/preregistrations_form.csv'
preregistrations_form.each_with_index do |row, index|
next if index.zero?
values = row.first.split ';'
email = values[7]
first_name = values[3]
city = Cities.find values[6]
preregistrations[email] = {
email: email,
first_name: first_name,
city: city
}
end
File.open('./tmp/legacy/preregistrations.csv', 'w') do |file|
file.puts preregistrations.values.map { |p| "#{p[:email]};#{p[:first_name]};#{p[:city]}" }.join("\n")
end
end
task import_users: :environment do |args|
desc "rake legacy:import_users url=https://url_du_csv"
if ENV.has_key?('url')
url = ENV['url']
csv = CSV.new open(url), headers: :first_row
else
csv = CSV.read './tmp/legacy/users.csv'
end
csv.each_with_index do |line, index|
next if index.zero?
user = User.where(email: line[1]).first_or_initialize
user.created_at = line[11]
user.encrypted_password = line[2]
user.last_name = line[20]
user.first_name = line[21]
user.host = line[14] == 'true'
photo = line[24]
unless photo.blank?
id_padded = line[0].to_s.rjust(3, '0')
url = "https://paupiette.s3-eu-central-1.amazonaws.com/users/images/000/000/#{id_padded}/original/#{photo}"
file = open(URI.escape(url))
user.photo.attach(io: file, filename: photo, content_type: file.content_type_parse.first)
end
city = City.where(name: line[15]).first
user.city = city unless city.nil?
user.save validate: false
puts "#{user.email}, #{user.first_name} #{user.last_name} @ #{user.city}"
end
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/application_controller.rb
|
class ApplicationController < ActionController::Base
include DevisePermittedParams
add_breadcrumb 'Paupiette', :root_path
end
|
AssociationPaupiette/paupiette
|
app/models/preregistration.rb
|
<filename>app/models/preregistration.rb<gh_stars>0
# == Schema Information
#
# Table name: preregistrations
#
# id :bigint(8) not null, primary key
# first_name :string
# email :string
# city_id :bigint(8)
# created_at :datetime not null
# updated_at :datetime not null
#
class Preregistration < ApplicationRecord
belongs_to :city, optional: true
validates_presence_of :email
validates_uniqueness_of :email
def self.import(csv)
csv.lines.each do |line|
import_line line
end
end
protected
def self.import_line(line)
values = line.split ';'
email = values[0].strip
first_name = values[1].strip
city_name = values[2].strip
preregistration = where(email: email).first_or_create
preregistration.first_name = first_name
city = City.where(name: city_name).first
preregistration.city = city unless city.nil?
preregistration.save
end
end
|
AssociationPaupiette/paupiette
|
test/mailers/previews/message_received_mailer_preview.rb
|
# Preview all emails at http://localhost:3000/rails/mailers/message_received_mailer
class MessageReceivedMailerPreview < ActionMailer::Preview
end
|
AssociationPaupiette/paupiette
|
app/models/user.rb
|
<reponame>AssociationPaupiette/paupiette
# == Schema Information
#
# Table name: users
#
# id :bigint(8) not null, primary key
# email :string default(""), not null
# encrypted_password :string default(""), not null
# reset_password_token :string
# reset_password_sent_at :datetime
# remember_created_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# first_name :string
# description :text
# specialties :text
# reception_days :string
# city_id :bigint(8)
# last_name :string
# host :boolean default(FALSE)
# admin :boolean default(FALSE)
# slug :string default(""), not null
# active :boolean default(TRUE), not null
# approved :boolean default(FALSE)
# address :string
# zipcode :string
# city :string
#
class User < ApplicationRecord
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable
serialize :reception_days, Array
belongs_to :city, optional: true
has_many :ambassadorships, dependent: :destroy
has_many :managed_cities, through: :ambassadorships, source: :city
has_and_belongs_to_many :conversations
has_many :messages_sent, class_name: 'Message', foreign_key: :from_id, dependent: :destroy
has_many :reviews_received, class_name: 'User::Review', foreign_key: :about_id, dependent: :destroy
has_many :reviews_given, class_name: 'User::Review', foreign_key: :from_id, dependent: :destroy
has_many :meals, foreign_key: :host_id
has_one_attached :photo
has_one_attached :identity_card
validates_presence_of :first_name, :last_name, :city_id, on: :update_profile
validates_presence_of :slug
validates_uniqueness_of :slug
before_validation :set_default_slug, on: :create
before_validation :strip_slug
before_destroy { conversations.clear }
after_validation :geocode, if: -> (user) { user.address.present? && user.address_changed? }
# Every user is a guest
scope :guests, -> {}
scope :hosts, -> { where(host: true) }
scope :not_hosts, -> { where(host: false) }
scope :ambassadors, -> { includes(:ambassadorships).where.not(ambassadorships: { user_id: nil }) }
scope :not_ambassadors, -> { where.not(id: ambassadors) }
scope :admins, -> { where(admin: true) }
scope :not_admins, -> { where(admin: false) }
scope :approved, -> { where(approved: true) }
scope :not_approved, -> { where(approved: false) }
scope :to_approve, -> { not_approved.joins(identity_card_attachment: :blob) }
scope :search, -> (term) {
where(' email LIKE ?
OR slug LIKE ?
OR first_name LIKE ?
OR last_name LIKE ?',
"%#{term}%",
"%#{term}%",
"%#{term}%",
"%#{term}%")
}
default_scope { order(:last_name, :first_name) }
geocoded_by :full_address
def full_name
"#{first_name} #{last_name}".strip
end
def to_s
full_name.blank? ? "Utilisateur anonyme #{id}" : "#{full_name}"
end
def to_short_s
first_name.blank? ? "Utilisateur anonyme #{id}" : "#{first_name}"
end
def full_address
"#{address}, #{zipcode}".strip
end
def localized_reception_days
days = I18n.t("date.day_names").rotate
return reception_days.map { |index| days[index.to_i].capitalize }
end
def ambassador?
self.managed_cities.count > 0
end
def conversation_with?(user)
!Conversation.between(user, self).nil?
end
def review_about(user)
reviews_given.where(about: user).first_or_initialize
end
def unread_messages_count
count = 0
conversations.each do |conversation|
count += conversation.messages_to(self).unread.count
end
count
end
def reduced_latitude
return nil if latitude.nil?
(latitude * 1000).ceil / 1000.0
end
def reduced_longitude
return nil if longitude.nil?
(longitude * 1000).ceil / 1000.0
end
private
def set_default_slug
create_slug
while slug_already_in_use?
create_slug
end
end
def create_slug
self.slug = SecureRandom.uuid
end
def slug_already_in_use?
User.where(slug: self.slug).where.not(id: id).exists?
end
def strip_slug
self.slug.strip!
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/ambassadors_controller.rb
|
class AmbassadorsController < ApplicationController
add_breadcrumb 'Ambassadeurs'
def index
@users = User.ambassadors.page params[:page]
end
end
|
AssociationPaupiette/paupiette
|
config/routes.rb
|
<reponame>AssociationPaupiette/paupiette<filename>config/routes.rb
Rails.application.routes.draw do
devise_for :users
namespace 'admin' do
resources 'ambassadorships'
resources 'cities' do
member do
get 'ambassadors'
get 'guests'
get 'hosts'
get 'preregistrations'
end
end
resources 'users' do
collection do
get 'admins'
get 'ambassadors'
get 'hosts'
get 'guests'
get 'search'
end
end
get 'preregistrations' => 'preregistrations#index'
post 'preregistrations' => 'preregistrations#import'
root to: 'dashboard#index'
end
namespace 'my' do
get 'messages' => 'messages#index'
get 'messages/:user_slug' => 'messages#user', as: :conversation
post 'messages/:user_slug' => 'messages#create', as: :send_message
get 'profile' => 'profile#index'
put 'profile' => 'profile#update'
get 'reviews' => 'reviews#index'
post 'reviews/:user_slug' => 'reviews#save', as: :review
patch 'reviews/:user_slug' => 'reviews#save'
resources 'meals'
root to: 'dashboard#index'
end
namespace 'my_cities' do
scope ':city_slug' do
scope 'users' do
get 'approval' => 'users#approval', as: :users_approval
get 'hosts' => 'users#hosts', as: :users_hosts
post ':user_slug/approve' => 'users#approve', as: :user_approve
post ':user_slug/unapprove' => 'users#unapprove', as: :user_unapprove
root to: 'users#index', as: :users
end
scope 'reviews' do
get 'approval' => 'reviews#approval', as: :reviews_approval
post ':id/approve' => 'reviews#approve', as: :review_approve
post ':id/unapprove' => 'reviews#unapprove', as: :review_unapprove
root to: 'reviews#index', as: :reviews
end
end
root to: 'application#index'
end
post 'preregistrations' => 'preregistrations#create'
get 'users/:user_slug' => 'users#show', as: :user
get 'hosts' => 'hosts#index'
get 'hosts/:city_slug' => 'hosts#city', as: :city_hosts
get 'ambassadors' => 'ambassadors#index'
get 'press' => 'pages#press'
get 'who' => 'pages#who'
get 'legal' => 'pages#legal'
root to: 'pages#index'
end
|
AssociationPaupiette/paupiette
|
app/models/city.rb
|
# == Schema Information
#
# Table name: cities
#
# id :bigint(8) not null, primary key
# name :string
# created_at :datetime not null
# updated_at :datetime not null
# active :boolean default(FALSE)
# slug :string default(""), not null
# latitude :float
# longitude :float
#
class City < ApplicationRecord
has_many :users
has_many :ambassadorships
has_many :ambassadors, through: :ambassadorships, source: :user
has_many :conversations, through: :users
has_many :preregistrations
has_many :reviews, through: :users, source: :reviews_received
has_many :meals, through: :users
validates_uniqueness_of :slug
before_validation :set_slug
scope :active, -> { where(active: true) }
scope :inactive, -> { where(active: false) }
default_scope { order(:name) }
def inactive?
!active?
end
def guests
users.guests
end
def hosts
users.hosts
end
def to_s
"#{name}"
end
protected
def set_slug
self.slug = name.parameterize
end
end
|
AssociationPaupiette/paupiette
|
app/helpers/dashboard/application_helper.rb
|
<gh_stars>0
module Dashboard::ApplicationHelper
end
|
AssociationPaupiette/paupiette
|
app/controllers/my/dashboard_controller.rb
|
class My::DashboardController < My::ApplicationController
def index
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/admin/application_controller.rb
|
class Admin::ApplicationController < ApplicationController
before_action :authenticate_user!
layout 'admin/layouts/application'
add_breadcrumb 'Admin', :admin_root_path
rescue_from CanCan::AccessDenied do |exception|
render file: "#{Rails.root}/public/403", formats: [:html], status: 403, layout: false
end
end
|
AssociationPaupiette/paupiette
|
db/migrate/20181113084330_add_lat_long_to_city.rb
|
class AddLatLongToCity < ActiveRecord::Migration[5.2]
def change
add_column :cities, :latitude, :float
add_column :cities, :longitude, :float
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/admin/cities_controller.rb
|
<gh_stars>0
class Admin::CitiesController < Admin::ApplicationController
load_and_authorize_resource
add_breadcrumb 'Villes', :admin_cities_path
def index
@cities = City.all
end
def new
@city = City.new
add_breadcrumb 'Nouvelle ville'
end
def show
add_breadcrumb @city
end
def preregistrations
add_breadcrumb @city, [:admin, @city]
add_breadcrumb 'Préinscriptions'
@preregistrations = @city.preregistrations
end
def ambassadors
add_breadcrumb @city, [:admin, @city]
add_breadcrumb 'Ambassadeurs'
@users = @city.ambassadors.page params[:page]
end
def guests
add_breadcrumb @city, [:admin, @city]
add_breadcrumb 'Convives'
@users = @city.guests.page params[:page]
end
def hosts
add_breadcrumb @city, [:admin, @city]
add_breadcrumb 'Hôtes'
@users = @city.hosts.page params[:page]
end
def edit
add_breadcrumb @city, [:admin, @city]
add_breadcrumb 'Modifier'
end
def create
@city = City.new city_params
if @city.save
redirect_to [:admin, @city], notice: 'La ville a été créée'
else
add_breadcrumb 'Nouvelle ville'
render :new
end
end
def update
@city.update city_params
if @city.save
redirect_to [:admin, @city], notice: 'La ville a été modifiée'
else
add_breadcrumb 'Modifier'
render :edit
end
end
private
def city_params
params.require(:city).permit(:name, :active, :latitude, :longitude)
end
end
|
AssociationPaupiette/paupiette
|
db/migrate/20181026095233_add_city_ref_to_users.rb
|
<reponame>AssociationPaupiette/paupiette
class AddCityRefToUsers < ActiveRecord::Migration[5.2]
def change
add_reference :users, :city, foreign_key: true
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/my_cities/users_controller.rb
|
class MyCities::UsersController < MyCities::ApplicationController
def index
@users = @city.users.guests.page params[:page]
add_breadcrumb t('my_cities.users.guests')
end
def hosts
@users = @city.users.hosts.page params[:page]
add_breadcrumb t('my_cities.users.hosts')
end
def approval
@users = @city.users.to_approve
add_breadcrumb t('my_cities.users.to_approve')
end
def approve
@user = User.find_by slug: params[:user_slug]
if !@user.nil? && @user.city.in?(current_user.managed_cities)
@user.approved = true
@user.save
flash[:notice] = 'Utilisateur approuvé'
else
flash[:notice] = 'Problème technique'
end
redirect_to my_cities_users_approval_path(city_slug: params[:city_slug])
end
def unapprove
@user = User.find_by slug: params[:user_slug]
if !@user.nil? && @user.city.in?(current_user.managed_cities)
@user.approved = false
@user.save
flash[:notice] = 'Utilisateur désapprouvé'
else
flash[:notice] = 'Problème technique'
end
redirect_to my_cities_root_path
end
end
|
AssociationPaupiette/paupiette
|
app/helpers/dashboard/profile_helper.rb
|
module Dashboard::ProfileHelper
end
|
AssociationPaupiette/paupiette
|
app/models/message.rb
|
# == Schema Information
#
# Table name: messages
#
# id :bigint(8) not null, primary key
# from_id :bigint(8)
# content :text
# read_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# conversation_id :integer
#
class Message < ApplicationRecord
belongs_to :from, class_name: "User"
belongs_to :conversation, touch: true
scope :received_from, -> (user) { where(from_id: user.id) }
scope :read, -> { where.not(read_at: nil) }
scope :unread, -> { where(read_at: nil) }
after_create :send_mail
def to
return if conversation.nil?
conversation.users.where.not(id: from).first
end
def mark_as_read_by!(user)
if self.read_at.nil?
self.read_at = DateTime.now
save
end
end
def to_s
"#{content}"
end
protected
def send_mail
MessageMailer.with(from: from, to: to).notification_email.deliver_later
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/my/application_controller.rb
|
class My::ApplicationController < ApplicationController
add_breadcrumb I18n.t('my.name'), :my_root_path
before_action :authenticate_user!
end
|
SLP-KBIT/LinkUS
|
app/models/group.rb
|
# == Schema Information
#
# Table name: groups
#
# id :integer not null, primary key
# name :string
# created_at :datetime not null
# updated_at :datetime not null
#
class Group < ActiveRecord::Base
has_many :group_users
has_many :users, through: :group_users
validates_uniqueness_of :name
end
|
SLP-KBIT/LinkUS
|
db/schema.rb
|
<gh_stars>1-10
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20151019083402) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "group_users", force: :cascade do |t|
t.integer "user_id"
t.integer "group_id"
t.integer "position"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "group_users", ["group_id"], name: "index_group_users_on_group_id", using: :btree
add_index "group_users", ["user_id"], name: "index_group_users_on_user_id", using: :btree
create_table "groups", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "oauth_access_grants", force: :cascade do |t|
t.integer "resource_owner_id", null: false
t.integer "application_id", null: false
t.string "token", null: false
t.integer "expires_in", null: false
t.text "redirect_uri", null: false
t.datetime "created_at", null: false
t.datetime "revoked_at"
t.string "scopes"
end
add_index "oauth_access_grants", ["token"], name: "index_oauth_access_grants_on_token", unique: true, using: :btree
create_table "oauth_access_tokens", force: :cascade do |t|
t.integer "resource_owner_id"
t.integer "application_id"
t.string "token", null: false
t.string "refresh_token"
t.integer "expires_in"
t.datetime "revoked_at"
t.datetime "created_at", null: false
t.string "scopes"
end
add_index "oauth_access_tokens", ["refresh_token"], name: "index_oauth_access_tokens_on_refresh_token", unique: true, using: :btree
add_index "oauth_access_tokens", ["resource_owner_id"], name: "index_oauth_access_tokens_on_resource_owner_id", using: :btree
add_index "oauth_access_tokens", ["token"], name: "index_oauth_access_tokens_on_token", unique: true, using: :btree
create_table "oauth_applications", force: :cascade do |t|
t.string "name", null: false
t.string "uid", null: false
t.string "secret", null: false
t.text "redirect_uri", null: false
t.string "scopes", default: "", null: false
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "oauth_applications", ["uid"], name: "index_oauth_applications_on_uid", unique: true, using: :btree
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.integer "failed_attempts", default: 0, null: false
t.string "unlock_token"
t.datetime "locked_at"
t.string "sid", null: false
t.string "name"
t.integer "laboratory", default: 0, null: false
t.integer "position", default: 0, null: false
t.string "phone", default: "", null: false
t.string "address"
t.date "birthday"
t.integer "role", default: 0, null: false
t.integer "status", default: 0, null: false
t.string "provider"
t.string "uid"
t.string "token"
t.text "raw"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["uid"], name: "index_users_on_uid", unique: true, using: :btree
add_index "users", ["unlock_token"], name: "index_users_on_unlock_token", unique: true, using: :btree
create_table "white_lists", force: :cascade do |t|
t.string "email", null: false
t.boolean "active", default: true, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
|
SLP-KBIT/LinkUS
|
config/deploy/production.rb
|
set :stage, :production
set :branch, 'master'
set :rails_env, 'production'
set :migration_role, 'db'
set :deploy_to, '/home/app/UnivWare/linkus'
server 'c4', user: ENV['PRODUCTION_USER'], roles: %w(web app db)
set :ssh_options, {
keys: [File.expand_path('~/.ssh/id_rsa')],
forward_agent: true,
auth_methods: %w(publickey)
}
|
SLP-KBIT/LinkUS
|
app/api/linkus/api.rb
|
<filename>app/api/linkus/api.rb
module Linkus
require 'v1/base'
class API < Grape::API
logger = Logger.new GrapeLogging::MultiIO.new(STDOUT, File.open('log/grape.log', 'a')), 'daily'
logger.formatter = GrapeLogging::Formatters::Default.new
use GrapeLogging::Middleware::RequestLogger, logger: logger
mount V1::Base
end
end
|
SLP-KBIT/LinkUS
|
app/decorators/group_user_decorator.rb
|
<filename>app/decorators/group_user_decorator.rb<gh_stars>1-10
class GroupUserDecorator < Draper::Decorator
delegate_all
def name_and_position
"#{object.group.name}(#{GroupUser::POSITION[object.position]})"
end
end
|
SLP-KBIT/LinkUS
|
config.ru
|
require 'unicorn/worker_killer'
use Unicorn::WorkerKiller::MaxRequests, 3072, 4096
use Unicorn::WorkerKiller::Oom, (192 * (1024**2)), (256 * (1024**2))
require ::File.expand_path('../config/environment', __FILE__)
if ENV['RAILS_RELATIVE_URL_ROOT']
map ENV['RAILS_RELATIVE_URL_ROOT'] do
run Rails.application
end
else
run Rails.application
end
|
SLP-KBIT/LinkUS
|
config/routes.rb
|
<filename>config/routes.rb
Rails.application.routes.draw do
use_doorkeeper
mount Linkus::API => '/api'
devise_for :users, controllers: {
omniauth_callbacks: 'users/omniauth_callbacks'
}
root 'users#index'
resources :users
namespace :admin do
resources :users, except: [:new, :create] do
post :lock, on: :member
post :unlock, on: :member
end
end
end
|
SLP-KBIT/LinkUS
|
app/models/user.rb
|
<gh_stars>1-10
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string default(""), not null
# encrypted_password :string default(""), not null
# 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
# failed_attempts :integer default(0), not null
# unlock_token :string
# locked_at :datetime
# sid :string not null
# name :string
# laboratory :integer default(0), not null
# position :integer default(0), not null
# phone :string default(""), not null
# address :string
# birthday :date
# role :integer default(0), not null
# status :integer default(0), not null
# provider :string
# uid :string
# token :string
# raw :text
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ActiveRecord::Base
devise :database_authenticatable, :rememberable, :trackable, :validatable, :lockable, :omniauthable
has_many :group_users
has_many :groups, through: :group_users
before_save :update_sid!
before_save :check_status!
accepts_nested_attributes_for :group_users, reject_if: :all_blank, allow_destroy: true
validates_uniqueness_of :email
LABORATORY = %w(無所属 富永研 林研 八重樫研 垂水研 安藤研 最所研 その他).freeze
POSITION = %w(なし 会計 所長 副所長 会計 広報 物品 旅行 事務).freeze
module Select
ROLE = [['管理者', 100], ['一般', 0]]
LABORATORY = LABORATORY.map.with_index { |labo, i| [labo, i] }
POSITION = POSITION.map.with_index { |pos, i| [pos, i] }
end
def schema
{
uid: uid,
sid: sid,
name: name
}
end
def self.find_for_google_oauth2(auth)
return false unless check_email(auth.info.email)
user = User.where(email: auth.info.email).first
return update_google!(user, auth) if user
User.create(
name: auth.info.name,
provider: auth.provider,
uid: auth.uid,
email: auth.info.email,
token: auth.credentials.token,
password: <PASSWORD>[0, 20],
raw: auth.to_json
)
end
def update_without_current_password(params, *options)
params.delete(:current_password)
params.delete(:password) if params[:password].blank?
params.delete(:password_confirmation) if params[:password_confirmation].blank?
clean_up_passwords
update_attributes(params, *options)
end
def self.update_google!(user, auth)
user.update(
name: auth.info.name,
provider: auth.provider,
uid: auth.uid,
email: auth.info.email,
token: auth.credentials.token,
password: <PASSWORD>[0, 20],
raw: auth.to_json
)
user
end
def is_admin?
100 <= role
end
def is_verified?
100 <= status
end
def update_sid!
self.sid = email.split('@').first
end
def check_status!
flag = true
skip_columns = %w(
id
encrypted_password
reset_password_token
reset_password_sent_at
remember_created_at
sign_in_count
current_sign_in_at
last_sign_in_at
current_sign_in_ip
last_sign_in_ip
failed_attempts
unlock_token
locked_at
role
status
created_at
updated_at
)
self.class.columns.each do |col|
target = col.name
next if skip_columns.include?(target)
flag = false unless try(target).present?
end
self.status = flag ? 100 : 0
end
def self.check_email(email)
return true if WhiteList.where(active: true).pluck(:email).index(email)
return false unless email.split('@')[1].include?('kagawa-u.ac.jp')
true
end
end
|
SLP-KBIT/LinkUS
|
app/api/linkus/v1/users.rb
|
module Linkus::V1
class Users < Grape::API
resource :users do
desc 'get user information'
get 'me' do
current_resource_owner.schema
end
end
end
end
|
SLP-KBIT/LinkUS
|
config/deploy.rb
|
# config valid only for current version of Capistrano
lock '3.4.0'
set :application, 'linkus'
set :repo_url, 'https://github.com/SLP-KBIT/linkus.git'
set :scm, :git
set :format, :pretty
set :log_level, :debug
set :pty, true
set :linked_files, fetch(:linked_files, []).push('.env')
set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle')
set :keep_releases, 5
set :conditionally_migrate, true
set :deploy_via, :remote_cache
namespace :deploy do
desc 'Restart application'
task :restart do
invoke 'unicorn:restart'
end
after :publishing, :restart
end
|
SLP-KBIT/LinkUS
|
app/controllers/users_controller.rb
|
<reponame>SLP-KBIT/LinkUS<gh_stars>1-10
class UsersController < ApplicationController
before_action :authenticate_user!
before_action :verified_user!
def index
@search = User.ransack(params[:q])
@users = @search.result.page(params[:page]).per(20)
end
def edit
end
end
|
SLP-KBIT/LinkUS
|
config/deploy/staging.rb
|
set :stage, :production
set :branch, 'master'
set :rails_env, 'production'
set :migration_role, 'db'
set :deploy_to, '/home/rails/deploy/linkus'
server 'linkus_staging', user: 'rails', roles: %w(web app db)
set :ssh_options, {
keys: [File.expand_path('~/.ssh/id_rsa')],
forward_agent: true,
auth_methods: %w(publickey)
}
|
SLP-KBIT/LinkUS
|
spec/spec_helper.rb
|
<gh_stars>1-10
require 'codeclimate-test-reporter'
CodeClimate::TestReporter.start
require 'active_record'
require 'factory_girl_rails'
require 'database_cleaner'
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.include FactoryGirl::Syntax::Methods
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.order = :random
end
|
SLP-KBIT/LinkUS
|
app/models/white_list.rb
|
<reponame>SLP-KBIT/LinkUS
# == Schema Information
#
# Table name: white_lists
#
# id :integer not null, primary key
# email :string not null
# active :boolean default(TRUE), not null
# created_at :datetime not null
# updated_at :datetime not null
#
class WhiteList < ActiveRecord::Base
end
|
SLP-KBIT/LinkUS
|
app/controllers/users/omniauth_callbacks_controller.rb
|
<reponame>SLP-KBIT/LinkUS
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
@user = User.find_for_google_oauth2(request.env['omniauth.auth'])
if @user.persisted?
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'Google'
if session[:return_to]
sign_in @user
redirect_to session[:return_to]
session[:return_to] = nil
else
sign_in_and_redirect @user, event: :authentication
end
else
session['devise.google_data'] = request.env['omniauth.auth']
redirect_to new_user_session_url, alert: @user.errors
end
end
end
|
SLP-KBIT/LinkUS
|
app/models/group_user.rb
|
<filename>app/models/group_user.rb
# == Schema Information
#
# Table name: group_users
#
# id :integer not null, primary key
# user_id :integer
# group_id :integer
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class GroupUser < ActiveRecord::Base
belongs_to :user
belongs_to :group
POSITION = %w(なし リーダー サブリーダー).freeze
module Select
POSITION = POSITION.map.with_index { |pos, i| [pos, i] }
end
end
|
SLP-KBIT/LinkUS
|
db/seeds.rb
|
<filename>db/seeds.rb
%w(CEM ETR GMV WSP).each do |group|
Group.create(name: group)
end
|
SLP-KBIT/LinkUS
|
app/decorators/user_decorator.rb
|
class UserDecorator < Draper::Decorator
delegate_all
def last_sign_in_at
return '未ログイン' unless object.last_sign_in_at
object.last_sign_in_at.strftime('%Y/%m/%d %H:%M')
end
def laboratory
User::LABORATORY[object.laboratory]
end
def position
User::POSITION[object.position]
end
end
|
SLP-KBIT/LinkUS
|
db/migrate/20150718005838_create_group_users.rb
|
<filename>db/migrate/20150718005838_create_group_users.rb
class CreateGroupUsers < ActiveRecord::Migration
def change
create_table :group_users do |t|
t.integer :user_id
t.integer :group_id
t.integer :position
t.timestamps null: false
end
add_index :group_users, :user_id
add_index :group_users, :group_id
end
end
|
SLP-KBIT/LinkUS
|
app/api/linkus/v1/base.rb
|
require 'doorkeeper/grape/helpers'
module Linkus::V1
class Base < Grape::API
version 'v1', using: :path
format :json
helpers Doorkeeper::Grape::Helpers
before do
doorkeeper_authorize!
end
helpers do
def current_resource_owner
User.find_by(id: doorkeeper_token.resource_owner_id) if doorkeeper_token
end
end
mount Users
end
end
|
SLP-KBIT/LinkUS
|
config/application.rb
|
<gh_stars>1-10
require File.expand_path('../boot', __FILE__)
require 'rails'
require 'active_model/railtie'
require 'active_job/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require 'sprockets/railtie'
Bundler.require(*Rails.groups)
module Linkus
class Application < Rails::Application
config.time_zone = 'Tokyo'
config.active_record.default_timezone = :local
config.i18n.default_locale = :ja
config.generators.template_engine = :slim
config.generators.helper = false
config.generators.assets = false
config.autoload_paths += %W(#{config.root}/lib)
config.active_record.raise_in_transactional_callbacks = true
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api')]
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]
end
end
|
SLP-KBIT/LinkUS
|
config/unicorn/production.rb
|
app_path = '/home/app/UnivWare/linkus'
app_shared_path = "#{app_path}/shared"
worker_processes 3
working_directory "#{app_path}/current"
listen "#{app_shared_path}/tmp/sockets/unicorn.sock"
stdout_path "#{app_shared_path}/log/unicorn.stdout.log"
stderr_path "#{app_shared_path}/log/unicorn.stderr.log"
pid "#{app_shared_path}/tmp/pids/unicorn.pid"
preload_app true
before_exec do |_|
ENV['BUNDLE_GEMFILE'] = "#{app_path}/current/Gemfile"
end
before_fork do |server, worker|
ActiveRecord::Base.connection.disconnect! if defined?(ActiveRecord::Base)
old_pid = "#{ server.config[:pid] }.oldbin"
unless old_pid == server.pid
begin
Process.kill :QUIT, File.read(old_pid).to_i
rescue Errno::ENOENT, Errno::ESRCH
end
end
end
after_fork do |server, worker|
ActiveRecord::Base.establish_connection if defined?(ActiveRecord::Base)
end
|
SLP-KBIT/LinkUS
|
app/controllers/admin/users_controller.rb
|
class Admin::UsersController < ApplicationController
before_action :authenticate_user!
before_action :admin_user!
before_action :load_user, except: [:index, :new, :create]
def index
@search = User.search(params[:q])
@users = @search.result.page(params[:page]).per(20)
end
def edit
render :show_modal_form
end
def update
@user.update_without_current_password(user_params)
render :reload
end
def destroy
@user.destroy
render :reload
end
def lock
@user.lock_access!
render :reload
end
def unlock
@user.unlock_access!
render :reload
end
private
def user_params
params.require(:user).permit(
:birthday, :role, :laboratory, :position, :phone, :address,
group_users_attributes: [:id, :group_id, :position, :_destroy]
)
end
def load_user
return unless params[:id]
@user = User.find_by(id: params[:id])
end
end
|
composetools/Compose
|
Compose.podspec
|
<reponame>composetools/Compose
Pod::Spec.new do |s|
s.name = 'Compose'
s.version = '1.0'
s.summary = 'Compose is a library that helps you compose complex and dynamic views.'
s.description = <<-DESC
Compose is a data-driven library that will help encapsulate and isolate all the information needed to display a view inside some container (UICollectionView/UITableView), so you don't need to handle with all dataSource/delegate methods.
DESC
s.homepage = 'https://github.com/vivareal/Compose'
s.documentation_url = 'https://vivareal.github.io/Compose/index.html'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '<NAME>' => '<EMAIL>' }
s.source = { :git => 'https://github.com/vivareal/Compose.git', :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
s.frameworks = 'UIKit'
s.source_files = 'Compose/Classes/**/*'
end
|
BorisDuan/BLBaseUtils
|
BLBaseUtils.podspec
|
#
# Be sure to run `pod lib lint BLBaseUtils.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 = 'BLBaseUtils'
s.version = '0.0.3'
s.summary = '彼恋基础组件'
# 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 = <<-DESC
彼恋基础组件,包含网络封装、本地数据封装、常量定义等等
DESC
s.homepage = 'https://github.com/BorisDuan/BLBaseUtils'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'BorisDuan' => '<EMAIL>' }
s.source = { :git => 'https://github.com/BorisDuan/BLBaseUtils.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '11.0'
s.swift_versions = ['5.0']
# s.source_files = 'BLBaseUtils/Classes/**/*'
s.subspec 'Extension' do |ss|
ss.source_files = 'BLBaseUtils/Classes/Extension/*.{swift}'
end
s.subspec 'HttpRequest' do |ss|
ss.source_files = 'BLBaseUtils/Classes/HttpRequest/*.{swift}'
end
s.subspec 'Assets' do |ss|
ss.source_files = 'BLBaseUtils/Assets/*.{swift}'
end
s.subspec 'Constants' do |ss|
ss.source_files = 'BLBaseUtils/Constants/*.{swift}'
end
# s.resource_bundles = {
# 'BLBaseUtils' => ['BLBaseUtils/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
s.frameworks = 'UIKit', 'Foundation'
s.dependency 'SwiftyJSON'
s.dependency 'Alamofire'
end
|
zpx2012/zeek_3.0.8
|
aux/zeek-aux/devel-tools/gen-mozilla-ca-list.rb
|
<reponame>zpx2012/zeek_3.0.8
#!/usr/bin/env ruby
tmpcert = "/tmp/tmpcert.der"
incert=false
intrust=false
if ARGV.length != 1
abort "\nPass path to the certdata.txt you want to add as first input argument to this script\n\n"+
"certdata.txt can be retrieved from the newest NSS release."
end
url = 'http://mxr.mozilla.org/mozilla-central/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1'
io = open(ARGV[0]);
puts "# Don't edit! This file is automatically generated."
puts "# Generated at: #{Time.now}"
puts "# Generated from: #{url}"
puts "#"
puts "# The original source file comes with this licensing statement:"
puts "#"
puts "# This Source Code Form is subject to the terms of the Mozilla Public"
puts "# License, v. 2.0. If a copy of the MPL was not distributed with this"
puts "# file, You can obtain one at http://mozilla.org/MPL/2.0/."
puts ""
puts "@load base/protocols/ssl"
puts "module SSL;";
puts "redef root_certs += {";
all_certs = []
all_subjects = []
cert_name = ""
cert = ""
io.each do |line|
line.chomp!
if intrust
if line =~ /^CKA_TRUST_SERVER_AUTH/
if line =~ /CKT_NSS_TRUSTED_DELEGATOR/
File.open(tmpcert, "wb") do |f|
byteArray = cert.split("\\x")
max = byteArray.length() - 1
byteArray[1..max].each do | byte |
f.print byte.hex.chr
end
end
cert_subj = `openssl x509 -in #{tmpcert} -inform DER -noout -subject -nameopt RFC2253`
cert_subj["subject= "]= ""
cert_subj.chomp!
File.delete(tmpcert)
if not all_subjects.include?(cert_subj)
puts " [\"#{cert_subj}\"] = \"#{cert}\","
all_subjects << cert_subj
end
end
intrust=false
end
else
if line =~ /^CKA_LABEL/
cert_name = line.sub(/.*\"(.*)\".*/, "\\1")
i = 0
while all_certs.include?(cert_name)
i+=1
cert_name += " #{i}"
end
all_certs << cert_name
elsif line =~ /^CKA_VALUE MULTILINE_OCTAL/
incert=true
cert=""
elsif line =~ /^CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST/
intrust=true
elsif line =~ /^END/
incert=false
elsif incert
cert += line.split(/\\/).collect { |x| x.oct.chr.unpack("H2")[0].upcase if x!="" }.join("\\x")
end
end
end
puts "};"
|
fercreek/humanize
|
lib/humanize/locales/jp.rb
|
<reponame>fercreek/humanize
require_relative 'constants/jp'
module Humanize
class Jp
def humanize(number)
iteration = 0
parts = []
until number.zero?
number, remainder = number.divmod(10000)
unless remainder.zero?
add_grouping(parts, iteration)
parts << SUB_ONE_GROUPING[remainder]
end
iteration += 1
end
parts
end
private
def add_grouping(parts, iteration)
grouping = LOTS[iteration]
return unless grouping
parts << "#{grouping}"
end
end
end
|
iuriivolochai/ios-app
|
Scripts/gen_loc_keys.rb
|
source_file_path = './TokenDWalletTemplate/Resources/Base.lproj/Localizable.strings'
target_file_path = './TokenDWalletTemplate/Sources/LocKey.swift'
source_content = File.read(source_file_path)
source_content.encode!('UTF-16', undef: :replace, invalid: :replace, replace: '')
source_content.encode!('UTF-8')
source_content_lines = source_content.lines
offset = ' '
loc_keys_string = "// This file is auto-generated\n\nimport Foundation\n\nenum LocKey: String {\n"
source_content_lines.each do |line|
keyValue = line.split('=')
next if keyValue.count < 2
keyPart = keyValue.first
keyPart = keyPart.sub('"', '').rstrip.chomp('"')
key = keyPart
loc_keys_string += offset
loc_keys_string += "case #{key}\n"
end
loc_keys_string += "}\n"
loc_keys_string.delete!("\x00")
target_file = File.open(target_file_path, 'w')
target_file.write(loc_keys_string)
target_file.close
|
raepad/Restaurant_CLI
|
lib/Restaurant_CLI.rb
|
<filename>lib/Restaurant_CLI.rb
require "Restaurant_CLI/version"
module RestaurantCLI
class Error < StandardError; end
# Your code goes here...
end
|
alphagov-mirror/omniauth-gds
|
lib/omniauth-gds.rb
|
<reponame>alphagov-mirror/omniauth-gds
require "omniauth-gds/version"
require "omniauth/strategies/gds"
|
alphagov-mirror/omniauth-gds
|
lib/omniauth/strategies/gds.rb
|
<reponame>alphagov-mirror/omniauth-gds<gh_stars>1-10
require 'omniauth-oauth2'
require 'multi_json'
class OmniAuth::Strategies::Gds < OmniAuth::Strategies::OAuth2
uid { user['uid'] }
info do
{
name: user['name'],
email: user['email']
}
end
extra do
{
user: user,
permissions: user['permissions'],
organisation_slug: user['organisation_slug'],
organisation_content_id: user['organisation_content_id'],
}
end
def user
@user ||= MultiJson.decode(access_token.get("/user.json?client_id=#{CGI.escape(options.client_id)}").body)['user']
end
end
|
alphagov-mirror/omniauth-gds
|
lib/omniauth-gds/version.rb
|
<reponame>alphagov-mirror/omniauth-gds
module Omniauth
module Gds
VERSION = "3.2.1"
end
end
|
mjobin-mdsol/faraday-http-cache
|
spec/request_spec.rb
|
<reponame>mjobin-mdsol/faraday-http-cache
# frozen_string_literal: true
require 'spec_helper'
describe Faraday::HttpCache::Request do
subject { Faraday::HttpCache::Request.new method: method, url: url, headers: headers }
let(:method) { :get }
let(:url) { URI.parse('http://example.com/path/to/somewhere') }
let(:headers) { {} }
context 'a GET request' do
it { should be_cacheable }
end
context 'a HEAD request' do
let(:method) { :head }
it { should be_cacheable }
end
context 'a POST request' do
let(:method) { :post }
it { should_not be_cacheable }
end
context 'a PUT request' do
let(:method) { :put }
it { should_not be_cacheable }
end
context 'an OPTIONS request' do
let(:method) { :options }
it { should_not be_cacheable }
end
context 'a DELETE request' do
let(:method) { :delete }
it { should_not be_cacheable }
end
context 'a TRACE request' do
let(:method) { :trace }
it { should_not be_cacheable }
end
context 'with "Cache-Control: no-store"' do
let(:headers) { { 'Cache-Control' => 'no-store' } }
it { should_not be_cacheable }
end
end
|
mjobin-mdsol/faraday-http-cache
|
lib/faraday/http_cache/cache_control.rb
|
# frozen_string_literal: true
module Faraday
class HttpCache < Faraday::Middleware
# Internal: A class to represent the 'Cache-Control' header options.
# This implementation is based on 'rack-cache' internals by <NAME>.
# It breaks the several directives into keys/values and stores them into
# a Hash.
class CacheControl
# Internal: Initialize a new CacheControl.
def initialize(header)
@directives = parse(header.to_s)
end
# Internal: Checks if the 'public' directive is present.
def public?
@directives['public']
end
# Internal: Checks if the 'private' directive is present.
def private?
@directives['private']
end
# Internal: Checks if the 'no-cache' directive is present.
def no_cache?
@directives['no-cache']
end
# Internal: Checks if the 'no-store' directive is present.
def no_store?
@directives['no-store']
end
# Internal: Gets the 'max-age' directive as an Integer.
#
# Returns nil if the 'max-age' directive isn't present.
def max_age
@directives['max-age'].to_i if @directives.key?('max-age')
end
# Internal: Gets the 'max-age' directive as an Integer.
#
# takes the age header integer value and reduces the max-age and s-maxage
# if present to account for having to remove static age header when caching responses
def normalize_max_ages(age)
if age > 0
@directives['max-age'] = @directives['max-age'].to_i - age if @directives.key?('max-age')
@directives['s-maxage'] = @directives['s-maxage'].to_i - age if @directives.key?('s-maxage')
end
end
# Internal: Gets the 's-maxage' directive as an Integer.
#
# Returns nil if the 's-maxage' directive isn't present.
def shared_max_age
@directives['s-maxage'].to_i if @directives.key?('s-maxage')
end
alias s_maxage shared_max_age
# Internal: Checks if the 'must-revalidate' directive is present.
def must_revalidate?
@directives['must-revalidate']
end
# Internal: Checks if the 'proxy-revalidate' directive is present.
def proxy_revalidate?
@directives['proxy-revalidate']
end
# Internal: Gets the String representation for the cache directives.
# Directives are joined by a '=' and then combined into a single String
# separated by commas. Directives with a 'true' value will omit the '='
# sign and their value.
#
# Returns the Cache Control string.
def to_s
booleans = []
values = []
@directives.each do |key, value|
if value == true
booleans << key
elsif value
values << "#{key}=#{value}"
end
end
(booleans.sort + values.sort).join(', ')
end
private
# Internal: Parses the Cache Control string to a Hash.
# Existing whitespace will be removed and the string is split on commas.
# For each part everything before a '=' will be treated as the key
# and the exceeding will be treated as the value. If only the key is
# present then the assigned value will default to true.
#
# Examples:
# parse("max-age=600")
# # => { "max-age" => "600"}
#
# parse("max-age")
# # => { "max-age" => true }
#
# Returns a Hash.
def parse(header)
directives = {}
header.delete(' ').split(',').each do |part|
next if part.empty?
name, value = part.split('=', 2)
directives[name.downcase] = (value || true) unless name.empty?
end
directives
end
end
end
end
|
mjobin-mdsol/faraday-http-cache
|
spec/binary_spec.rb
|
<reponame>mjobin-mdsol/faraday-http-cache<filename>spec/binary_spec.rb
# frozen_string_literal: true
require 'spec_helper'
describe Faraday::HttpCache do
let(:client) do
Faraday.new(url: ENV['FARADAY_SERVER']) do |stack|
stack.use :http_cache, serializer: Marshal
adapter = ENV['FARADAY_ADAPTER']
stack.headers['X-Faraday-Adapter'] = adapter
stack.adapter adapter.to_sym
end
end
let(:data) { IO.binread File.expand_path('../support/empty.png', __FILE__) }
it 'works fine with binary data' do
expect(client.get('image').body).to eq data
expect(client.get('image').body).to eq data
end
end
|
mjobin-mdsol/faraday-http-cache
|
lib/faraday-http-cache.rb
|
<filename>lib/faraday-http-cache.rb
require 'faraday/http_cache'
|
mjobin-mdsol/faraday-http-cache
|
spec/instrumentation_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
require 'active_support'
require 'active_support/notifications'
describe 'Instrumentation' do
let(:backend) { Faraday::Adapter::Test::Stubs.new }
let(:client) do
Faraday.new do |stack|
stack.use Faraday::HttpCache, instrumenter: ActiveSupport::Notifications
stack.adapter :test, backend
end
end
let(:events) { [] }
let(:subscriber) { lambda { |*args| events << ActiveSupport::Notifications::Event.new(*args) } }
around do |example|
ActiveSupport::Notifications.subscribed(subscriber, 'http_cache.faraday') do
example.run
end
end
describe 'the :cache_status payload entry' do
it 'is :miss if there is no cache entry for the URL' do
backend.get('/hello') do
[200, { 'Cache-Control' => 'public, max-age=999' }, '']
end
client.get('/hello')
expect(events.last.payload.fetch(:cache_status)).to eq(:miss)
end
it 'is :fresh if the cache entry has not expired' do
backend.get('/hello') do
[200, { 'Cache-Control' => 'public, max-age=999' }, '']
end
client.get('/hello') # miss
client.get('/hello') # fresh!
expect(events.last.payload.fetch(:cache_status)).to eq(:fresh)
end
it 'is :valid if the cache entry can be validated against the upstream' do
backend.get('/hello') do
headers = {
'Cache-Control' => 'public, must-revalidate, max-age=0',
'Etag' => '123ABCD'
}
[200, headers, '']
end
client.get('/hello') # miss
backend.get('/hello') { [304, {}, ''] }
client.get('/hello') # valid!
expect(events.last.payload.fetch(:cache_status)).to eq(:valid)
end
it 'is :invalid if the cache entry could not be validated against the upstream' do
backend.get('/hello') do
headers = {
'Cache-Control' => 'public, must-revalidate, max-age=0',
'Etag' => '123ABCD'
}
[200, headers, '']
end
client.get('/hello') # miss
backend.get('/hello') { [200, {}, ''] }
client.get('/hello') # invalid!
expect(events.last.payload.fetch(:cache_status)).to eq(:invalid)
end
end
end
|
mjobin-mdsol/faraday-http-cache
|
spec/spec_helper.rb
|
# frozen_string_literal: true
require 'uri'
require 'socket'
require 'faraday-http-cache'
require 'faraday_middleware'
# https://github.com/rails/rails/pull/14667
require 'active_support/per_thread_registry'
require 'active_support/cache'
require 'support/test_app'
require 'support/test_server'
server = TestServer.new
ENV['FARADAY_SERVER'] = server.endpoint
ENV['FARADAY_ADAPTER'] ||= 'net_http'
server.start
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.order = 'random'
config.after(:suite) do
server.stop
end
end
|
mjobin-mdsol/faraday-http-cache
|
spec/validation_spec.rb
|
<gh_stars>10-100
# frozen_string_literal: true
require 'spec_helper'
describe Faraday::HttpCache do
let(:backend) { Faraday::Adapter::Test::Stubs.new }
let(:client) do
Faraday.new(url: ENV['FARADAY_SERVER']) do |stack|
stack.use Faraday::HttpCache
stack.adapter :test, backend
end
end
it 'maintains the "Content-Type" header for cached responses' do
backend.get('/test') { [200, { 'ETag' => '123ABC', 'Content-Type' => 'x' }, ''] }
first_content_type = client.get('/test').headers['Content-Type']
# The Content-Type header of the validation response should be ignored.
backend.get('/test') { [304, { 'Content-Type' => 'y' }, ''] }
second_content_type = client.get('/test').headers['Content-Type']
expect(first_content_type).to eq('x')
expect(second_content_type).to eq('x')
end
it 'maintains the "Content-Length" header for cached responses' do
backend.get('/test') { [200, { 'ETag' => '123ABC', 'Content-Length' => 1 }, ''] }
first_content_length = client.get('/test').headers['Content-Length']
# The Content-Length header of the validation response should be ignored.
backend.get('/test') { [304, { 'Content-Length' => 2 }, ''] }
second_content_length = client.get('/test').headers['Content-Length']
expect(first_content_length).to eq(1)
expect(second_content_length).to eq(1)
end
end
|
mjobin-mdsol/faraday-http-cache
|
spec/cache_control_spec.rb
|
<gh_stars>10-100
# frozen_string_literal: true
require 'spec_helper'
describe Faraday::HttpCache::CacheControl do
it 'takes a String with multiple name=value pairs' do
cache_control = Faraday::HttpCache::CacheControl.new('max-age=600, max-stale=300, min-fresh=570')
expect(cache_control.max_age).to eq(600)
end
it 'takes a String with a single flag value' do
cache_control = Faraday::HttpCache::CacheControl.new('no-cache')
expect(cache_control).to be_no_cache
end
it 'takes a String with a bunch of all kinds of stuff' do
cache_control =
Faraday::HttpCache::CacheControl.new('max-age=600,must-revalidate,min-fresh=3000,foo=bar,baz')
expect(cache_control.max_age).to eq(600)
expect(cache_control).to be_must_revalidate
end
it 'strips leading and trailing spaces' do
cache_control = Faraday::HttpCache::CacheControl.new(' public, max-age = 600 ')
expect(cache_control).to be_public
expect(cache_control.max_age).to eq(600)
end
it 'ignores blank segments' do
cache_control = Faraday::HttpCache::CacheControl.new('max-age=600,,s-maxage=300')
expect(cache_control.max_age).to eq(600)
expect(cache_control.shared_max_age).to eq(300)
end
it 'sorts alphabetically with boolean directives before value directives' do
cache_control = Faraday::HttpCache::CacheControl.new('foo=bar, z, x, y, bling=baz, zoom=zib, b, a')
expect(cache_control.to_s).to eq('a, b, x, y, z, bling=baz, foo=bar, zoom=zib')
end
it 'responds to #max_age with an integer when max-age directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('public, max-age=600')
expect(cache_control.max_age).to eq(600)
end
it 'responds to #max_age with nil when no max-age directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('public')
expect(cache_control.max_age).to be_nil
end
it 'responds to #shared_max_age with an integer when s-maxage directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('public, s-maxage=600')
expect(cache_control.shared_max_age).to eq(600)
end
it 'responds to #shared_max_age with nil when no s-maxage directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('public')
expect(cache_control.shared_max_age).to be_nil
end
it 'responds to #public? truthfully when public directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('public')
expect(cache_control).to be_public
end
it 'responds to #public? non-truthfully when no public directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('private')
expect(cache_control).not_to be_public
end
it 'responds to #private? truthfully when private directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('private')
expect(cache_control).to be_private
end
it 'responds to #private? non-truthfully when no private directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('public')
expect(cache_control).not_to be_private
end
it 'responds to #no_cache? truthfully when no-cache directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('no-cache')
expect(cache_control).to be_no_cache
end
it 'responds to #no_cache? non-truthfully when no no-cache directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('max-age=600')
expect(cache_control).not_to be_no_cache
end
it 'responds to #must_revalidate? truthfully when must-revalidate directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('must-revalidate')
expect(cache_control).to be_must_revalidate
end
it 'responds to #must_revalidate? non-truthfully when no must-revalidate directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('max-age=600')
expect(cache_control).not_to be_must_revalidate
end
it 'responds to #proxy_revalidate? truthfully when proxy-revalidate directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('proxy-revalidate')
expect(cache_control).to be_proxy_revalidate
end
it 'responds to #proxy_revalidate? non-truthfully when no proxy-revalidate directive present' do
cache_control = Faraday::HttpCache::CacheControl.new('max-age=600')
expect(cache_control).not_to be_no_cache
end
end
|
mjobin-mdsol/faraday-http-cache
|
examples/parallel.rb
|
require 'rubygems'
require 'bundler/setup'
require 'faraday/http_cache'
require 'active_support/logger'
require 'em-http-request'
client = Faraday.new('https://api.github.com') do |stack|
stack.use :http_cache, logger: ActiveSupport::Logger.new(STDOUT)
stack.adapter :em_http
end
2.times do
started = Time.now
client.in_parallel do
client.get('repos/plataformatec/faraday-http-cache')
client.get('repos/lostisland/faraday')
end
finished = Time.now
puts " Parallel requests done! #{(finished - started) * 1000} ms."
puts
end
|
k-o-d-e-n/ScreenUI
|
ScreenUI.podspec
|
<gh_stars>1-10
#
# Be sure to run `pod lib lint ScreenUI.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 = 'ScreenUI'
s.version = '1.1.1'
s.summary = 'A multi-platform, multi-paradigm routing framework. `UIKit`, `AppKit`, `SwiftUI`'
s.description = <<-DESC
A multi-platform, multi-paradigm routing framework for iOS/macOS and others, the replacement of Storyboard. Supports `UIKit`, `AppKit`, `SwiftUI`.
DESC
s.homepage = 'https://github.com/k-o-d-e-n/ScreenUI'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'k-o-d-e-n' => '<EMAIL>' }
s.source = { :git => 'https://github.com/k-o-d-e-n/ScreenUI.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/K_o_D_e_N'
s.swift_version = '5.3'
s.ios.deployment_target = '9.0'
s.macos.deployment_target = '10.15'
s.tvos.deployment_target = '9.0'
s.watchos.deployment_target = '7.0'
s.default_subspec = 'Release'
s.subspec 'Release' do |r|
r.source_files = 'Sources/ScreenUI/**/*'
r.exclude_files = 'Sources/**/*.gyb'
end
s.subspec 'Beta' do |b|
b.dependency 'ScreenUI/Release'
b.pod_target_xcconfig = {
'SWIFT_ACTIVE_COMPILATION_CONDITIONS[config=Debug]' => '$(inherited) SCREENUI_BETA'
}
end
end
|
jonny-rawlin/movie-maker
|
app/controllers/directors_controller.rb
|
class DirectorsController < ApplicationController
# GET: /directors
get "/directors" do
@directors = Director.all
erb :"/directors/index.html"
end
# GET: /directors/new
get "/directors/new" do
erb :"/directors/new.html"
end
# POST: /directors
post "/directors" do
director = Director.new(name: params[:director][:name], age: params[:director][:age], nationality: params[:director][:nationality])
redirect "/directors"
end
# GET: /directors/5
get "/directors/:id" do
@director = Director.find(params[:id])
erb :"/directors/show.html"
end
# GET: /directors/5/edit
get "/directors/:id/edit" do
erb :"/directors/edit.html"
end
# PATCH: /directors/5
patch "/directors/:id" do
redirect "/directors/:id"
end
# DELETE: /directors/5/delete
delete "/directors/:id/delete" do
redirect "/directors"
end
end
|
jonny-rawlin/movie-maker
|
app/controllers/movies_controller.rb
|
<reponame>jonny-rawlin/movie-maker<gh_stars>0
class MoviesController < ApplicationController
# GET: /movies
get "/movies" do
@movies = Movie.all
erb :"/movies/index.html"
end
# GET: /movies/new
get "/movies/new" do
erb :"/movies/new.html"
end
# POST: /movies
post "/movies" do
@movie = Movie.new(name: params[:movies][:name], genre: params[:movies][:genre], release_date: params[:movies][:release_date])
params[:movies][:director].each do |director|
director = Director.new(director)
director.movies = movie
director.save
end
params[:movies][:actors].each do |actor|
actor = Actor.new(actor)
actor.movies = movie
actor.save
end
redirect "/movies"
end
# GET: /movies/5
get "/movies/:id" do
@movie = Movie.find(params[:id])
erb :"/movies/show.html"
end
# GET: /movies/5/edit
get "/movies/:id/edit" do
erb :"/movies/edit.html"
end
# PATCH: /movies/5
patch "/movies/:id" do
redirect "/movies/:id"
end
# DELETE: /movies/5/delete
delete "/movies/:id/delete" do
redirect "/movies"
end
end
|
jonny-rawlin/movie-maker
|
app/models/movie.rb
|
class Movie < ActiveRecord::Base
has_many :actors
belongs_to :director
end
|
jonny-rawlin/movie-maker
|
app/controllers/actors_controller.rb
|
class ActorsController < ApplicationController
# GET: /actors
get "/actors" do
@actors = Actor.all
erb :"/actors/index.html"
end
# GET: /actors/new
get "/actors/new" do
erb :"/actors/new.html"
end
# POST: /actors
post "/actors" do
actor = Actor.new(name: params[:actor][:name], age: params[:actor][:age], nationality: params[:actor][:nationality])
redirect "/actors"
end
# GET: /actors/5
get "/actors/:id" do
@actor = Actor.find(params[:id])
erb :"/actors/show.html"
end
# GET: /actors/5/edit
get "/actors/:id/edit" do
erb :"/actors/edit.html"
end
# PATCH: /actors/5
patch "/actors/:id" do
redirect "/actors/:id"
end
# DELETE: /actors/5/delete
delete "/actors/:id/delete" do
redirect "/actors"
end
end
|
aks/validate_suffixed_number
|
lib/validate_suffixed_number.rb
|
# frozen_string_literal: true
# Class to parse and validate suffixed numbers.
class ValidateSuffixedNumber
# methods for validating strings as optionally suffixed numbers (floats or integers)
SI_MULTIPLIERS = {
'hundred': 10**2,
'thousand': 10**3, 'K': 10**3, # kilo
'million': 10**6, 'M': 10**6, # mega
'billion': 10**9, 'B': 10**9, 'G': 10**9, # giga
'trillion': 10**12, 'T': 10**12, # tera
'quadrillion': 10**15, 'P': 10**15, # peta
'quintillion': 10**18, 'E': 10**18, # exa
'sextillion': 10**21, 'Z': 10**21, # zeta
'septillion': 10**24, 'Y': 10**24, # yotta
}.freeze
SI_ABBREVIATIONS = SI_MULTIPLIERS.keys.select { |k| k.length == 1 }
SI_MAGNIFIERS = SI_MULTIPLIERS.keys.select { |k| k.length > 1 }
ABBREVIATIONS_RE = /^((?:[+-]\s*)?\d[\d_]*(?:\.\d*)?)\s*([#{SI_ABBREVIATIONS}])$/i
MAGNIFIERS_RE = /^((?:[+-]\s*)?\d[\d_]*(?:\.\d*)?)\s*(#{SI_MAGNIFIERS.join('|')})$/i
SCIENTIFIC_RE = /^(?:[+-]\s*)?\d[\d_]*(?:\.\d*)?[Ee][+-]?\d+$/
FLOAT_RE = /^(?:[+-]\s*)?\d[\d_]*(?:\.\d*)?$/
INTEGER_RE = /^(?:[+-]\s*)?\d[\d_]*$/
class << self
def parse_numeric_option(key, options, error_msg = nil)
parse_value_option(key, options, :parse_number, error_msg)
end
def parse_integer_option(key, options, error_msg = nil)
parse_value_option(key, options, :parse_integer, error_msg)
end
def parse_integer(string_arg)
parse_number(string_arg)&.to_i
end
def parse_number(string_arg)
str = string_arg&.strip
if SCIENTIFIC_RE.match?(str) # scientific notation?
str.to_f
elsif (mdata = MAGNIFIERS_RE.match(str))
# eg: 1.2 billion, 12 trillion, 1500 thousand, 15000
suffix = mdata[2].downcase.to_sym
mdata[1].sub(' ', '').to_f * SI_MULTIPLIERS[suffix]
elsif (mdata = ABBREVIATIONS_RE.match(str))
# eg: 1.2G, 12T, 1500K, 15000
suffix = mdata[2].upcase.to_sym
mdata[1].gsub(' ', '').to_f * SI_MULTIPLIERS[suffix]
elsif FLOAT_RE.match?(str)
str.sub(' ', '').to_f
elsif INTEGER_RE.match?(str)
str.sub(' ', '').to_i
end
end
private
def parse_value_option(key, options, validator, error_msg = nil)
options ||= {}
arg = options[key]&.strip
error("No value given for --#{key}") if arg.nil?
(options[key] = send(validator, arg)) ||
error_message(error_msg || "Bad value for --#{key}: '%s'", arg)
end
def error_message(msg, arg)
if msg.include?('%s')
error sprintf(msg, arg)
else
error "#{msg}: '#{arg}'"
end
end
def error(msg)
raise ArgumentError, msg
end
end
end
|
aks/validate_suffixed_number
|
spec/spec_helper.rb
|
<filename>spec/spec_helper.rb
# spec_helper.rb
$LOAD_PATH << File.join(__dir__, '..', 'lib')
require 'validate_suffixed_number'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.