repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/spec/fabricators/meal_fabricator.rb | spec/fabricators/meal_fabricator.rb | # == Schema Information
#
# Table name: meals
#
# id :integer not null, primary key
# date :date
# calories :integer
# carbohydrates :integer
# protein :integer
# fat :integer
# user_id :integer
# description :string(255)
# created_at :datetime
# updated_at :datetime
#
Fabricator(:meal) do
date "2013-03-30 12:37:56 -0400"
calories 100
carbohydrates 20
fat 30
protein 10
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/spec/fabricators/weight_fabricator.rb | spec/fabricators/weight_fabricator.rb | # == Schema Information
#
# Table name: weights
#
# id :integer not null, primary key
# type :string(255)
# user_id :integer
# bmi :float
# value :float
# lean_mass :float
# fat_mass :float
# fat_percent :float
# date :datetime
# created_at :datetime
# updated_at :datetime
# meta :hstore
# source :string(255)
#
Fabricator(:weight) do
value 0.0
date "2013-03-30 12:37:56 -0400"
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/spec/fabricators/foursquare_account_fabricator.rb | spec/fabricators/foursquare_account_fabricator.rb | # == Schema Information
#
# Table name: foursquare_accounts
#
# id :integer not null, primary key
# uid :string(255)
# oauth_token :string(255)
# activated_at :datetime
# synced_at :datetime
# user_id :integer
# created_at :datetime
# updated_at :datetime
#
Fabricator(:foursquare_account) do
oauth_token "0"
uid "0"
activated_at Date.current
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/spec/fabricators/user_fabricator.rb | spec/fabricators/user_fabricator.rb | # == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# created_at :datetime
# updated_at :datetime
# email :string(255) default(""), not null
# encrypted_password :string(255) default(""), not null
# reset_password_token :string(255)
# reset_password_sent_at :datetime
# remember_created_at :datetime
# confirmation_token :string(255)
# confirmed_at :datetime
# confirmation_sent_at :datetime
# unconfirmed_email :string(255)
# failed_attempts :integer default(0)
# unlock_token :string(255)
# locked_at :datetime
# name :string(255)
# height :float
# time_zone :string(255) default("UTC")
#
Fabricator(:user) do
name { Faker::Name.name }
height 10.0
email { |attrs| "#{attrs[:name].parameterize}@local.dev" }
password 'changeme'
password_confirmation 'changeme'
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/spec/fabricators/sleep_fabricator.rb | spec/fabricators/sleep_fabricator.rb | # == Schema Information
#
# Table name: sleeps
#
# id :integer not null, primary key
# start :datetime
# end :datetime
# user_id :integer
# created_at :datetime
# updated_at :datetime
# meta :hstore
# source :string(255)
#
Fabricator(:sleep) do |f|
start "2013-03-10 12:37:56 -0400"
f.end "2013-03-11 12:37:56 -0400"
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/spec/fabricators/fitbit_account_fabricator.rb | spec/fabricators/fitbit_account_fabricator.rb | # == Schema Information
#
# Table name: fitbit_accounts
#
# id :integer not null, primary key
# uid :string(255)
# oauth_token :string(255)
# oauth_token_secret :string(255)
# user_id :integer
# created_at :datetime
# updated_at :datetime
# synced_at :datetime
# activated_at :datetime
#
Fabricator(:fitbit_account) do
oauth_token "0"
oauth_token_secret "0"
uid "0"
activated_at Date.current
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/lib/exceptions.rb | lib/exceptions.rb | module Exceptions
class ApiError < StandardError; end
class DataProviderForMethodNotDefined < NoMethodError; end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/application.rb | config/application.rb | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Quantify
class Application < Rails::Application
VERSION = "0.0.13"
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
config.autoload_paths += %W(
#{config.root}/lib
#{config.root}/app/controllers/concerns
#{config.root}/app/models/concerns
)
# http://stackoverflow.com/questions/20361428/rails-i18n-validation-deprecation-warning
config.i18n.enforce_available_locales = false
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password, :password_confirmation, :feelings, :happiness, :strategies]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = VERSION
config.autoload_paths += %W(
models
extensions/models
).map{|path| File.join(config.root,'app',path)}
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :fabraction, dir: 'spec/fabricators'
g.view_specs false
g.helper_specs false
g.stylesheets = false
g.javascripts = false
g.helper = false
end
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/environment.rb | config/environment.rb | # Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
Quantify::Application.initialize!
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/routes.rb | config/routes.rb | Quantify::Application.routes.draw do
resources :journal_entries
authenticated :user do
get '/', to: "dashboard#index"
end
get '/', to: 'home#index'
devise_for :users, controllers: {
registrations: "registrations",
omniauth_callbacks: "omniauth_callbacks"
}
resources :dashboard, only: [:index]
resources :home, only: [:index]
resources :users, only: [:show]
resources :places
resources :weights
resources :meals
resources :sleeps
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id))(.:format)'
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/unicorn.rb | config/unicorn.rb | worker_processes 3
timeout 30
preload_app true
before_fork do |server, worker|
# Replace with MongoDB or whatever
if defined?(ActiveRecord::Base)
ActiveRecord::Base.connection.disconnect!
Rails.logger.info('Disconnected from ActiveRecord')
end
# If you are using Redis but not Resque, change this
# if defined?(Resque)
# Resque.redis.quit
# Rails.logger.info('Disconnected from Redis')
# end
sleep 1
end
after_fork do |server, worker|
# Replace with MongoDB or whatever
if defined?(ActiveRecord::Base)
ActiveRecord::Base.establish_connection
Rails.logger.info('Connected to ActiveRecord')
end
# If you are using Redis but not Resque, change this
# if defined?(Resque)
# Resque.redis = ENV['REDIS_URI']
# Rails.logger.info('Connected to Redis')
# end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/boot.rb | config/boot.rb | require 'rubygems'
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/unit.rb | config/initializers/unit.rb | class Unit
# inspired by http://stackoverflow.com/a/15269518
SYSTEMS = [:metric, :imperial]
IMPERIAL = %w(:inches :feet :miles :pounds)
METRIC = %w(:centimeters :meters :kilometers :kilograms)
@@conversion_rates = {
meters: {
feet: 3.28084,
meters: 1.0,
centimeters: 100,
kilograms: 1.0
},
centimeters: {
meters: 0.01
},
kilograms: {
pounds: 2.2046
},
pounds: {
kilograms: 0.453592,
pounds: 1.0
},
feet: {
inches: 12.0,
meters: 0.3048,
feet: 1.0
}
}
@@conversion_types = {
metric: {
inches: :centimeters,
feet: :meters,
miles: :kilometers,
pounds: :kilograms
},
imperial: {
centimeters: :inches,
meters: :feet,
kilometers: :miles,
kilograms: :pounds
},
centimeters: :metric,
meters: :metric,
kilometers: :metric,
kilograms: :metric,
inches: :imperial,
feet: :imperial,
miles: :imperial,
pounds: :imperial
}
def initialize(length, unit)
@length = length
@unit = unit
@system = system
end
def to_unit(new_unit)
return @length if @unit == new_unit
@length * @@conversion_rates[@unit][new_unit]
end
def to_system(new_system)
return @length if @system == new_system
unit = @@conversion_types[new_system][@unit]
to_unit(unit)
end
def system
@@conversion_types[@unit]
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/time_formats.rb | config/initializers/time_formats.rb | # config/initializers/time_formats.rb
Time::DATE_FORMATS[:day_month_and_year] = '%d %b %Y'
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/session_store.rb | config/initializers/session_store.rb | # Be sure to restart your server when you modify this file.
Quantify::Application.config.session_store :cookie_store, key: '_quantify_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# Quantify::Application.config.session_store :active_record_store
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/devise.rb | config/initializers/devise.rb | # Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
config.secret_key = Settings.devise_secret_key
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = Settings.devise_mailer_sender
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing :skip => :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = 'a540d33b0a229adee97a4bbd34b0dc2a20fa6bb5f10c765ba8f938550b3be3f4db5ee8c23790d06ea6d40c552cc170e5ef481f2ae5622158ef41d86166a6d16e'
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 8..128.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = false
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: "/my_engine"
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = "/my_engine/users/auth"
config.allow_unconfirmed_access_for = 14.days
config.omniauth :withings, Settings.withings_oauth_key, Settings.withings_oauth_secret
config.omniauth :fitbit, Settings.fitbit_oauth_key, Settings.fitbit_oauth_secret
config.omniauth :foursquare, Settings.foursquare_oauth_key, Settings.foursquare_oauth_secret
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/rails_config.rb | config/initializers/rails_config.rb | RailsConfig.setup do |config|
config.const_name = "Settings"
end | ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/withings.rb | config/initializers/withings.rb | Withings.configure(Settings.withings_oauth_key, Settings.withings_oauth_secret)
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/wrap_parameters.rb | config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
#
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = false
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/inflections.rb | config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
#
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.acronym 'RESTful'
# end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/json_escape.rb | config/initializers/json_escape.rb | class ActionView::Base
def json_escape(s)
result = s.to_s.gsub('/', '\/')
s.html_safe? ? result.html_safe : result
end
alias j json_escape
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/warden_callbacks.rb | config/initializers/warden_callbacks.rb | Warden::Manager.after_authentication do |user,auth,opts|
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/backtrace_silencers.rb | config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/mime_types.rb | config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/initializers/secret_token.rb | config/initializers/secret_token.rb | if Rails.env.test? || Rails.env.development? || Rails.env == "profile"
Quantify::Application.config.secret_token = "8ae1beeb1dbcda5851624d6dbf1c6656827e54d81c025501a7a23e09801ec2eee0f05625218ec45479bb28eb23c60fd73a89ae0e3e6cf5fbce0c2c13da6fd89b"
Quantify::Application.config.secret_key_base = "c6e66601cd5d4b6183ac99d88421f303b8bda479dfc6f8bcb5a89c6ed7c54bf62ee26ba9c49de98608d0209549ba1e666ed87dcf0ec988146af628efc13e7c2f"
else
raise "You must set a secret token in ENV['SECRET_TOKEN'] or in config/initializers/secret_token.rb" if !Settings.secret_token
Quantify::Application.config.secret_token = Settings.secret_token
Quantify::Application.config.secret_key_base = Settings.secret_key_base
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/environments/test.rb | config/environments/test.rb | Quantify::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
config.action_mailer.raise_delivery_errors = false
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/environments/development.rb | config/environments/development.rb | Quantify::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
config.middleware.use Rack::LiveReload
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { :host => "localhost:3000" }
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Expands the lines which load the assets
config.assets.debug = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => Settings.smtp_address,
:port => Settings.smtp_port,
:domain => Settings.smtp_domain,
:user_name => Settings.smtp_user_name,
:password => Settings.smtp_password,
:authentication => Settings.smtp_authentication,
:enable_starttls_auto => true }
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/config/environments/production.rb | config/environments/production.rb | Quantify::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Do not eager load code on boot.
config.eager_load = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.js_compressor = :uglifier
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
config.logger = Logger.new(STDOUT)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
if Settings.asset_host
config.action_controller.asset_host = Settings.asset_host
end
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { :host => Settings.action_mailer_default_url_options_host }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => Settings.smtp_address,
:port => Settings.smtp_port,
:domain => Settings.smtp_domain,
:user_name => Settings.smtp_user_name,
:password => Settings.smtp_password,
:authentication => Settings.smtp_authentication,
:enable_starttls_auto => true }
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
config.logger = Logger.new(STDOUT)
# Mandated by a Heroku bug: http://stackoverflow.com/questions/17300341/migrate-not-working-on-heroku
config.active_record.schema_format = :ruby
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
ayastreb/jekyll-maps | https://github.com/ayastreb/jekyll-maps/blob/14109e9917dbdc03b710981a464f8860b12a828e/spec/options_parser_spec.rb | spec/options_parser_spec.rb | require "spec_helper"
describe Jekyll::Maps::OptionsParser do
context "parses filters" do
it "ignores extra whitespaces" do
actual = Jekyll::Maps::OptionsParser.parse(" foo_key = 'bar' moo = 'baz'")
expected = {
"foo_key" => "bar",
"moo" => "baz"
}
expect(actual[:filters]).to eq(expected)
end
it "parses double quotes" do
actual = Jekyll::Maps::OptionsParser.parse('foo="bar"')
expected = {
"foo" => "bar"
}
expect(actual[:filters]).to eq(expected)
end
it "parses single argument" do
actual = Jekyll::Maps::OptionsParser.parse("foo='bar'")
expected = {
"foo" => "bar"
}
expect(actual[:filters]).to eq(expected)
end
it "parses multiple arguments" do
actual = Jekyll::Maps::OptionsParser.parse("foo='bar' moo='baz'")
expected = {
"foo" => "bar",
"moo" => "baz"
}
expect(actual[:filters]).to eq(expected)
end
it "parses multiple values in argument" do
actual = Jekyll::Maps::OptionsParser.parse("foo='bar,baz'")
expected = {
"foo" => %w(bar baz)
}
expect(actual[:filters]).to eq(expected)
end
it "parses multiple words in argument" do
actual = Jekyll::Maps::OptionsParser.parse("foo='bar baz' moo = 'mar maz'")
expected = {
"foo" => "bar baz",
"moo" => "mar maz"
}
expect(actual[:filters]).to eq(expected)
end
end
context "parses attributes" do
it "parses predefined attributes" do
actual = Jekyll::Maps::OptionsParser.parse(
"id='foo' width='100' height='50%' class='my-css-class,another-class'"
)
expected = {
:id => "foo",
:width => "100",
:height => "50%",
:class => %w(my-css-class another-class)
}
expect(actual[:attributes]).to eq(expected)
end
end
context "parses flags" do
it "parses all allowed flags correctly" do
actual = Jekyll::Maps::OptionsParser.parse("no_cluster")
expected = {
:no_cluster => true
}
expect(actual[:flags]).to eq(expected)
end
end
end
| ruby | MIT | 14109e9917dbdc03b710981a464f8860b12a828e | 2026-01-04T17:44:16.897613Z | false |
ayastreb/jekyll-maps | https://github.com/ayastreb/jekyll-maps/blob/14109e9917dbdc03b710981a464f8860b12a828e/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "simplecov"
SimpleCov.start
require "jekyll"
require "jekyll-maps"
Jekyll.logger.log_level = :error
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.order = "random"
SOURCE_DIR = File.expand_path("../fixtures", __FILE__)
DEST_DIR = File.expand_path("../dest", __FILE__)
def source_dir(*files)
File.join(SOURCE_DIR, *files)
end
def dest_dir(*files)
File.join(DEST_DIR, *files)
end
CONFIG_DEFAULTS = {
"source" => source_dir,
"destination" => dest_dir,
"gems" => ["jekyll-maps"],
"collections" => ["my_collection"],
"maps" => {
"google" => {
"api_key" => "GOOGLE_MAPS_API_KEY"
}
}
}.freeze
def make_page(options = {})
page = Jekyll::Page.new(site, CONFIG_DEFAULTS["source"], "", "page.md")
page.data = options
page
end
def make_site(options = {})
site_config = Jekyll.configuration(CONFIG_DEFAULTS.merge(options))
Jekyll::Site.new(site_config)
end
def make_context(registers = {}, environments = {})
Liquid::Context.new(
environments,
{},
{ :site => site, :page => page }.merge(registers)
)
end
def finds_all_pa_locations(_options, _finder, actual)
expect(actual.empty?).to be_falsey
pa_places = ["Pittsburgh", "Philadelphia", "Naylor Observatory"]
pa_places.each do |title|
expect(actual.find { |l| l[:title] == title }).to be_a(Hash)
end
end
def ignores_non_pa_locations(_options, _finder, actual)
non_pa_places = [
"Boston",
"New York",
"Apache Point Observatory",
"Adams Observatory",
"Paris",
"Madrid",
"Not a place"
]
non_pa_places.each do |title|
expect(actual.find { |l| l[:title] == title }).to be_nil
end
end
def search_data_for_pa_places(query)
let(:options) { Jekyll::Maps::OptionsParser.parse(query) }
let(:finder) { Jekyll::Maps::LocationFinder.new(options) }
let(:actual) { finder.find(site, page) }
it "ignores non-PA locations" do
finds_all_pa_locations(options, finder, actual)
end
it "finds all PA locations" do
ignores_non_pa_locations(options, finder, actual)
end
end
end
| ruby | MIT | 14109e9917dbdc03b710981a464f8860b12a828e | 2026-01-04T17:44:16.897613Z | false |
ayastreb/jekyll-maps | https://github.com/ayastreb/jekyll-maps/blob/14109e9917dbdc03b710981a464f8860b12a828e/spec/location_finder_spec.rb | spec/location_finder_spec.rb | require "spec_helper"
describe Jekyll::Maps::LocationFinder do
let(:site) { make_site }
let(:page) { make_page }
before :each do
site.process
end
context "looking for locations in posts" do
let(:options) { Jekyll::Maps::OptionsParser.parse("src='_posts'") }
let(:finder) { Jekyll::Maps::LocationFinder.new(options) }
let(:actual) { finder.find(site, page) }
it "finds posts with location" do
expect(actual).to all(be_a(Hash))
expect(actual).to all(include(:latitude, :longitude, :title, :url))
end
it "finds location in post" do
expect(actual.find { |l| l[:title] == "London" }).to be_a(Hash)
end
it "finds multiple locations in single post" do
# there should be 3 locations in post: fixtures/_posts/2017-06-19-multi-locations.md
barcelona_main = actual.find { |l| l[:title] == "Barcelona" }
expect(barcelona_main).to be_a(Hash)
expect(barcelona_main[:url]).to eq("")
expect(barcelona_main[:latitude]).to eq(41.3948976)
expect(barcelona_main[:longitude]).to eq(2.0787279)
expect(barcelona_main[:image]).to eq("/main-img.jpg")
barcelona_sagrada = actual.find { |l| l[:title] == "sagrada familia" }
expect(barcelona_sagrada[:url]).to eq("")
expect(barcelona_sagrada[:latitude]).to eq(41.4032671)
expect(barcelona_sagrada[:longitude]).to eq(2.1739832)
expect(barcelona_sagrada[:image]).to eq("/main-img.jpg")
barcelona_url = actual.find { |l| l[:title] == "location with url" }
expect(barcelona_url[:url]).to eq("/next-post")
expect(barcelona_url[:url_text]).to eq("Next Post")
expect(barcelona_url[:latitude]).to eq(41.3864518)
expect(barcelona_url[:longitude]).to eq(2.1890757)
expect(barcelona_url[:image]).to eq("/next-img.jpg")
end
it "skips posts without location" do
actual.each do |location|
expect(location).not_to include(:title => "post without location")
end
end
end
context "looking for locations in custom collections" do
let(:options) { Jekyll::Maps::OptionsParser.parse("src='_my_collection'") }
let(:finder) { Jekyll::Maps::LocationFinder.new(options) }
let(:actual) { finder.find(site, page) }
it "finds location in custom collections" do
expect(actual.find { |l| l[:title] == "Tokyo" }).to be_a(Hash)
end
end
context "looking for locations in data files with deep source (France)" do
let(:options) { Jekyll::Maps::OptionsParser.parse("src='_data/france/places.yml'") }
let(:finder) { Jekyll::Maps::LocationFinder.new(options) }
let(:actual) { finder.find(site, page) }
it "finds location from France" do
expect(actual.find { |l| l[:title] == "Paris" }).to be_a(Hash)
end
it "doesn't find location from Spain" do
actual.each do |location|
expect(location).not_to include(:title => "Madird")
end
end
end
context "looking for locations in data files with deep source (Spain)" do
let(:options) { Jekyll::Maps::OptionsParser.parse("src='_data/spain'") }
let(:finder) { Jekyll::Maps::LocationFinder.new(options) }
let(:actual) { finder.find(site, page) }
it "finds location from Spain" do
expect(actual.find { |l| l[:title] == "Madrid" }).to be_a(Hash)
end
it "doesn't find location from France" do
actual.each do |location|
expect(location).not_to include(:title => "Paris")
end
end
end
context "looking for locations in specific data file" do
let(:options) { Jekyll::Maps::OptionsParser.parse("src='_data/places.yaml'") }
let(:finder) { Jekyll::Maps::LocationFinder.new(options) }
let(:actual) { finder.find(site, page) }
it "finds locations in all data files" do
expect(actual.length).to eq(2)
expect(actual.find { |l| l[:title] == "Tokyo" }).to be_a(Hash)
expect(actual.find { |l| l[:title] == "New York" }).to be_a(Hash)
end
end
context "looking for locations in data files with shallow source" do
let(:options) { Jekyll::Maps::OptionsParser.parse("src='_data'") }
let(:finder) { Jekyll::Maps::LocationFinder.new(options) }
let(:actual) { finder.find(site, page) }
it "finds locations in all data files" do
expect(actual.find { |l| l[:title] == "Paris" }).to be_a(Hash)
expect(actual.find { |l| l[:title] == "Madrid" }).to be_a(Hash)
end
end
context "filtering posts by location" do
let(:options) { Jekyll::Maps::OptionsParser.parse("src='_posts' country='de'") }
let(:finder) { Jekyll::Maps::LocationFinder.new(options) }
let(:actual) { finder.find(site, page) }
it "finds only German locations" do
expect(actual.empty?).to be_falsey
actual.each do |location|
expect(location).to include(:title => "Berlin")
end
end
end
context "filtering data by location (state filter first)" do
search_data_for_pa_places("state='PA' src='_data'")
end
context "filtering data by location (src filter first)" do
search_data_for_pa_places("src='_data' state='PA'")
end
context "by default look for locations on current page" do
let(:location) { { "location" => { "latitude" => 1, "longitude" => -1 } } }
let(:page) { make_page(location) }
let(:options) { Jekyll::Maps::OptionsParser.parse("") }
let(:finder) { Jekyll::Maps::LocationFinder.new(options) }
let(:actual) { finder.find(site, page) }
it "finds only location from given page" do
expect(actual.length).to eq(1)
expect(actual.first[:latitude]).to eq(location["location"]["latitude"])
expect(actual.first[:longitude]).to eq(location["location"]["longitude"])
end
end
context "skip url if location does not have it" do
let(:options) { Jekyll::Maps::OptionsParser.parse("src='_data/no_url'") }
let(:finder) { Jekyll::Maps::LocationFinder.new(options) }
let(:actual) { finder.find(site, page) }
it "finds location without link" do
location = actual.find { |l| l[:title] == "No link" }
expect(location).to be_a(Hash)
expect(location[:url]).to eq("")
end
end
context "take location from inline attributes first" do
let(:options) do
attrs = %w(
latitude='42.2'
longitude='3.2'
marker_title='inline marker'
marker_img='/marker-img.jpg'
marker_url='/marker-url'
)
Jekyll::Maps::OptionsParser.parse(attrs.join(" "))
end
let(:finder) { Jekyll::Maps::LocationFinder.new(options) }
let(:actual) { finder.find(site, page) }
it "finds only location from attributes" do
expect(actual.empty?).to be_falsey
expect(actual.length).to eq(1)
location = actual.find { |l| l[:title] == "inline marker" }
expect(location).to be_a(Hash)
expect(location[:latitude]).to eq("42.2")
expect(location[:longitude]).to eq("3.2")
expect(location[:title]).to eq("inline marker")
expect(location[:image]).to eq("/marker-img.jpg")
expect(location[:url]).to eq("/marker-url")
end
end
end
| ruby | MIT | 14109e9917dbdc03b710981a464f8860b12a828e | 2026-01-04T17:44:16.897613Z | false |
ayastreb/jekyll-maps | https://github.com/ayastreb/jekyll-maps/blob/14109e9917dbdc03b710981a464f8860b12a828e/spec/google_map_tag_spec.rb | spec/google_map_tag_spec.rb | require "spec_helper"
describe Jekyll::Maps::GoogleMapTag do
let(:site) { make_site }
before { site.process }
context "full page rendering" do
let(:content) { File.read(dest_dir("page.html")) }
it "builds javascript" do
expect(content).to match(%r!#{Jekyll::Maps::GoogleMapTag::JS_LIB_NAME}!)
expect(content).to match(%r!(London|Paris)!)
end
it "does not include external js directly (should be lazy loaded)" do
expect(content.scan(%r!maps\.googleapis\.com!).length).to eq(0)
end
it "registers Google Maps for lazy loading" do
expect(content).to match(%r!js.src = "//maps.google.com/maps/!)
end
it "renders API key" do
expect(content).to match(%r!maps/api/js\?key=GOOGLE_MAPS_API_KEY!)
end
it "provides fallback method when IntersectionObserver is
not implemented/supported (older browsers)" do
expect(content).to match(%r!('IntersectionObserver' in window)!)
end
end
context "marker cluster disabled" do
let(:site) do
make_site({
"maps" => {
"google" => {
"marker_cluster" => {
"enabled" => false
}
}
}
})
end
let(:content) { File.read(dest_dir("page.html")) }
before :each do
site.process
end
it "does not load marker cluster external script" do
expect(content).not_to match(%r!script.*src=.*markerclusterer\.js!)
end
end
context "marker cluster enabled by default" do
let(:site) { make_site }
let(:content) { File.read(dest_dir("page.html")) }
before :each do
site.process
end
it "does load marker clusterer external script" do
expect(content).to match(%r!script.*src=.*markerclusterer\.js!)
end
end
context "options rendering" do
let(:page) { make_page }
let(:site) { make_site }
let(:context) { make_context(:page => page, :site => site) }
let(:tag) { "google_map" }
context "render all attributes" do
let(:options) do
"id='foo' width='100' height='50%' class='baz,bar' ignored='bad' zoom='5'"
end
let(:output) do
Liquid::Template.parse("{% #{tag} #{options} %}").render!(context, {})
end
it "renders attributes" do
expect(output).to match("div id='foo' style='width:100px;height:50%;'")
expect(output).to match("class='baz bar jekyll-map'")
end
it "renders custom zoom setting" do
expected = %r!"customZoom":5!
expect(output).to match(expected)
end
end
context "render default dimensions" do
let(:options) { "id='foo'" }
let(:output) do
Liquid::Template.parse("{% #{tag} #{options} %}").render!(context, {})
end
it "renders dimensions with default values" do
width = Jekyll::Maps::GoogleMapTag::DEFAULT_MAP_WIDTH
height = Jekyll::Maps::GoogleMapTag::DEFAULT_MAP_HEIGHT
expected = %r!div id='foo' style='width:#{width}px;height:#{height}px;'!
expect(output).to match(expected)
end
end
context "render with custom styles" do
let(:options) { "styles='fixture_style'" }
let(:output) do
Liquid::Template.parse("{% #{tag} #{options} %}").render!(context, {})
end
it "renders dimensions with default values" do
# styles content is loaded from fixtures/_data/maps_styles/fixture_style.json
expected = '"styles":[{"elementType":"geometry","stylers":[{"color":"#1d2c4d"}]}]'
expect(output).to include(expected)
end
end
end
end
| ruby | MIT | 14109e9917dbdc03b710981a464f8860b12a828e | 2026-01-04T17:44:16.897613Z | false |
ayastreb/jekyll-maps | https://github.com/ayastreb/jekyll-maps/blob/14109e9917dbdc03b710981a464f8860b12a828e/lib/jekyll-maps.rb | lib/jekyll-maps.rb | require "securerandom"
require "ostruct"
require "jekyll-maps/google_map_api"
require "jekyll-maps/google_map_tag"
require "jekyll-maps/location_finder"
require "jekyll-maps/options_parser"
require "jekyll-maps/version"
module Jekyll
module Maps
end
end
| ruby | MIT | 14109e9917dbdc03b710981a464f8860b12a828e | 2026-01-04T17:44:16.897613Z | false |
ayastreb/jekyll-maps | https://github.com/ayastreb/jekyll-maps/blob/14109e9917dbdc03b710981a464f8860b12a828e/lib/jekyll-maps/version.rb | lib/jekyll-maps/version.rb | module Jekyll
module Maps
VERSION = "2.4.0".freeze
end
end
| ruby | MIT | 14109e9917dbdc03b710981a464f8860b12a828e | 2026-01-04T17:44:16.897613Z | false |
ayastreb/jekyll-maps | https://github.com/ayastreb/jekyll-maps/blob/14109e9917dbdc03b710981a464f8860b12a828e/lib/jekyll-maps/google_map_api.rb | lib/jekyll-maps/google_map_api.rb | module Jekyll
module Maps
class GoogleMapApi
HEAD_END_TAG = %r!</[\s\t]*head>!
BODY_END_TAG = %r!</[\s\t]*body>!
class << self
def prepend_api_code(doc)
@config = doc.site.config
if doc.output =~ HEAD_END_TAG
# Insert API code before header's end if this document has one.
doc.output.gsub!(HEAD_END_TAG, %(#{api_code}#{Regexp.last_match}))
else
doc.output.prepend(api_code)
end
end
def prepend_google_api_code(doc)
@config = doc.site.config
if doc.output =~ BODY_END_TAG
# Insert API code before body's end if this document has one.
doc.output.gsub!(BODY_END_TAG, %(#{google_api_code}#{Regexp.last_match}))
else
doc.output.prepend(api_code)
end
end
private
def api_code
<<HTML
<script type='text/javascript'>
#{js_lib_contents}
</script>
HTML
end
private
def google_api_code
<<HTML
#{load_google_maps_api}
#{load_marker_cluster}
HTML
end
private
def load_google_maps_api
api_key = @config.fetch("maps", {})
.fetch("google", {})
.fetch("api_key", "")
<<HTML
<script async defer>
// Load maps only when DOM is loaded
document.addEventListener("DOMContentLoaded", function() {
if (window.google && window.google.maps && jekyllMaps) {
// Maps script already loaded -> Execute callback method
jekyllMaps.initializeMap();
} else if (!('IntersectionObserver' in window) ||
!('IntersectionObserverEntry' in window) ||
!('intersectionRatio' in window.IntersectionObserverEntry.prototype)) {
// Intersection Observer -> Backup solution : load maps now
lazyLoadGoogleMap();
} else {
// Google Maps not loaded & Intersection Observer working -> Enable it
enableMapsObserver();
}
});
function enableMapsObserver() {
// Enable Observer on all Maps
var maps = document.getElementsByClassName('jekyll-map');
const observer = new IntersectionObserver(function(entries, observer) {
// Test if one of the maps is in the viewport
var isIntersecting = typeof entries[0].isIntersecting === 'boolean' ? entries[0].isIntersecting : entries[0].intersectionRatio > 0;
if (isIntersecting) {
lazyLoadGoogleMap();
observer.disconnect();
}
});
for(var i = 0; i < maps.length; i++) {
observer.observe(maps[i]);
}
}
function lazyLoadGoogleMap() {
// If google maps api script not already loaded
if(!window.google || !window.google.maps) {
var fjs = document.getElementsByTagName('script')[0];
var js = document.createElement('script');
js.id = 'gmap-api';
js.setAttribute('async', '');
js.setAttribute('defer', '');
js.src = "//maps.google.com/maps/api/js?key=#{api_key}&callback=#{Jekyll::Maps::GoogleMapTag::JS_LIB_NAME}.initializeMap";
fjs.parentNode.insertBefore(js, fjs);
}
}
</script>
HTML
end
private
def load_marker_cluster
settings = @config.fetch("maps", {})
.fetch("google", {})
.fetch("marker_cluster", {})
return unless settings.fetch("enabled", true)
<<HTML
<script async defer src='https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/src/markerclusterer.js'
onload='#{Jekyll::Maps::GoogleMapTag::JS_LIB_NAME}.initializeCluster(#{settings.to_json})'></script>
HTML
end
private
def js_lib_contents
@js_lib_contents ||= begin
File.read(js_lib_path)
end
end
private
def js_lib_path
@js_lib_path ||= begin
File.expand_path("./google_map_api.js", File.dirname(__FILE__))
end
end
end
end
end
end
Jekyll::Hooks.register [:pages, :documents], :post_render do |doc|
if doc.output =~ %r!#{Jekyll::Maps::GoogleMapTag::JS_LIB_NAME}!
Jekyll::Maps::GoogleMapApi.prepend_api_code(doc)
Jekyll::Maps::GoogleMapApi.prepend_google_api_code(doc)
end
end
| ruby | MIT | 14109e9917dbdc03b710981a464f8860b12a828e | 2026-01-04T17:44:16.897613Z | false |
ayastreb/jekyll-maps | https://github.com/ayastreb/jekyll-maps/blob/14109e9917dbdc03b710981a464f8860b12a828e/lib/jekyll-maps/google_map_tag.rb | lib/jekyll-maps/google_map_tag.rb | module Jekyll
module Maps
class GoogleMapTag < Liquid::Tag
JS_LIB_NAME = "jekyllMaps".freeze
DEFAULT_MAP_WIDTH = 600
DEFAULT_MAP_HEIGHT = 400
def initialize(_, args, _)
@args = OptionsParser.parse(args)
@finder = LocationFinder.new(@args)
super
end
def render(context)
locations = @finder.find(context.registers[:site], context.registers[:page])
@args[:attributes][:id] ||= SecureRandom.uuid
<<HTML
<div #{render_attributes}></div>
<script type='text/javascript'>
#{JS_LIB_NAME}.register(
'#{@args[:attributes][:id]}',
#{locations.to_json},
#{map_options(context.registers[:site]).to_json}
);
</script>
HTML
end
private
def render_attributes
attributes = []
attributes << "id='#{@args[:attributes][:id]}'"
attributes << render_dimensions
attributes << render_class
attributes.join(" ")
end
private
def render_dimensions
width = @args[:attributes][:width] || DEFAULT_MAP_WIDTH
height = @args[:attributes][:height] || DEFAULT_MAP_HEIGHT
width_unit = width.to_s.include?("%") ? "" : "px"
height_unit = height.to_s.include?("%") ? "" : "px"
%(style='width:#{width}#{width_unit};height:#{height}#{height_unit};')
end
private
def render_class
css = @args[:attributes][:class]
css = css.join(" ") if css.is_a?(Array)
%(class='#{css} jekyll-map')
end
private
def render_styles(site)
style_name = @args[:attributes][:styles] || "default"
maps_styles = site.data["maps_styles"] || {}
maps_styles[style_name] || "[]"
end
private
def map_options(site)
opts = {
:baseUrl => site.baseurl || "/",
:useCluster => !@args[:flags][:no_cluster],
:showMarker => @args[:attributes][:show_marker] != "false",
:showMarkerPopup => @args[:attributes][:show_popup] != "false",
:markerIcon => @args[:attributes][:marker_icon],
:styles => render_styles(site)
}
if @args[:attributes][:zoom]
opts[:customZoom] = @args[:attributes][:zoom].to_i
end
opts
end
end
end
end
Liquid::Template.register_tag("google_map", Jekyll::Maps::GoogleMapTag)
| ruby | MIT | 14109e9917dbdc03b710981a464f8860b12a828e | 2026-01-04T17:44:16.897613Z | false |
ayastreb/jekyll-maps | https://github.com/ayastreb/jekyll-maps/blob/14109e9917dbdc03b710981a464f8860b12a828e/lib/jekyll-maps/location_finder.rb | lib/jekyll-maps/location_finder.rb | module Jekyll
module Maps
class LocationFinder
def initialize(options)
@documents = []
@options = options
end
def find(site, page)
if @options[:attributes][:latitude] && @options[:attributes][:longitude]
return [location_from_options(page)]
elsif @options[:filters].empty?
@documents << page if with_location?(page)
else
site.collections.each_value { |collection| filter(collection.docs) }
site_data(site).each_value { |items| traverse(items) }
end
documents_to_locations
end
private
def location_from_options(page)
{
:latitude => @options[:attributes][:latitude],
:longitude => @options[:attributes][:longitude],
:title => @options[:attributes][:marker_title] || page["title"],
:icon => @options[:attributes][:marker_icon] || page["marker_icon"],
:url => @options[:attributes][:marker_url] || fetch_url(page),
:image => @options[:attributes][:marker_img] || page["image"] || "",
:popup_html => @options[:attributes][:marker_popup_html] || ""
}
end
private
def site_data(site)
return {} unless data_source?
path = @options[:filters]["src"].scan(%r!_data\/([^\/]+)!).join(".")
return site.data if path.empty?
data = OpenStruct.new(site.data)
if @options[:filters]["src"] =~ %r!\.ya?ml!
{ :path => data[path.gsub(%r!\.ya?ml!, "")] }
else
data[path]
end
end
private
def data_source?
filters = @options[:filters]
filters.key?("src") && filters["src"].start_with?("_data")
end
private
def traverse(items)
return filter(items) if items.is_a?(Array)
items.each_value { |children| traverse(children) } if items.is_a?(Hash)
end
private
def filter(docs)
docs.each do |doc|
@documents << doc if with_location?(doc) && match_filters?(doc)
end
end
private
def with_location?(doc)
!doc["location"].nil? && !doc["location"].empty?
end
private
def match_filters?(doc)
@options[:filters].each do |filter, value|
if filter == "src"
if doc.respond_to?(:relative_path)
return false unless doc.relative_path.start_with?(value)
end
elsif doc[filter].nil? || doc[filter] != value
return false
end
end
return true
end
private
def documents_to_locations
locations = []
@documents.each do |document|
if document["location"].is_a?(Array)
document["location"].each do |location|
point = convert(document, location)
point[:url] = "" if point[:url] == fetch_url(document)
locations.push(point)
end
else
locations.push(convert(document, document["location"]))
end
end
locations
end
private
def convert(document, location)
{
:latitude => location["latitude"],
:longitude => location["longitude"],
:title => location["title"] || document["title"],
:icon => location["marker_icon"] || document["marker_icon"],
:url => location["url"] || fetch_url(document),
:url_text => location["url_text"],
:image => location["image"] || document["image"] || "",
:popup_html => location["marker_popup_html"] \
|| document["marker_popup_html"] || ""
}
end
private
def fetch_url(document)
return document["url"] if document.is_a?(Hash) && document.key?("url")
return document.url if document.respond_to? :url
""
end
end
end
end
| ruby | MIT | 14109e9917dbdc03b710981a464f8860b12a828e | 2026-01-04T17:44:16.897613Z | false |
ayastreb/jekyll-maps | https://github.com/ayastreb/jekyll-maps/blob/14109e9917dbdc03b710981a464f8860b12a828e/lib/jekyll-maps/options_parser.rb | lib/jekyll-maps/options_parser.rb | module Jekyll
module Maps
class OptionsParser
OPTIONS_SYNTAX = %r!([^\s]+)\s*=\s*['"]+([^'"]+)['"]+!
ALLOWED_FLAGS = %w(
no_cluster
).freeze
ALLOWED_ATTRIBUTES = %w(
id
width
height
class
show_marker
show_popup
zoom
latitude
longitude
marker_title
marker_icon
marker_img
marker_url
marker_popup_html
styles
).freeze
class << self
def parse(raw_options)
options = {
:attributes => {},
:filters => {},
:flags => {}
}
raw_options.scan(OPTIONS_SYNTAX).each do |key, value|
value = value.split(",") if value.include?(",")
if ALLOWED_ATTRIBUTES.include?(key)
options[:attributes][key.to_sym] = value
else
options[:filters][key] = value
end
end
ALLOWED_FLAGS.each do |key|
options[:flags][key.to_sym] = true if raw_options.include?(key)
end
options
end
end
end
end
end
| ruby | MIT | 14109e9917dbdc03b710981a464f8860b12a828e | 2026-01-04T17:44:16.897613Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/stats.rb | app/services/stats.rb |
class Stats
def initialize(stats_map)
@stats = []
dates = stats_map.keys.sort
dates.each_with_index do |date, index|
old_date = index == 0 ? nil : dates[index-1]
@stats << StatsEntry.new(date, stats_map[date], stats_map[old_date])
end
@stats.shift
end
def each(&block)
@stats.each(&block)
end
def average(key, use_changes: false)
mean(key, use_changes: use_changes) do |values|
(values.inject(:+).to_f / values.size).round(1)
end
end
def median(key, use_changes: false)
mean(key, use_changes: use_changes) do |values|
values[values.size/2]
end
end
private
def mean(key, use_changes:, &block)
values = @stats.map { |entry| entry.value(key) }
if use_changes
values = values.map(&:change)
end
result = block.call(values.map(&:to_i))
if use_changes && result > 0
"+#{result}"
else
result.to_s
end
end
class StatsEntry
def initialize(date, entry, prev_entry = nil)
@date = date
@entry = entry
@prev_entry = prev_entry || {}
fix_missing_keys
end
def value(key, add_change = true)
value = StatsValue.new(key, @entry[key].to_i, @prev_entry[key].to_i)
end
def val(key, add_change = true)
v = value(key, add_change)
str = v.to_s
if add_change
str << " (#{v.change_prefix}#{v.change})"
end
str
end
def shown_date
@date - 1
end
private
def fix_missing_keys
@entry["projects:badges:ruby"] = @entry["projects:badges"].to_i -
@entry["projects:badges:elixir"].to_i -
@entry["projects:badges:javascript"].to_i
end
end
class StatsValue < Struct.new(:key, :value, :old_value)
def change
value - old_value
end
def change_prefix
"+" if change > 0
end
def to_i
value.to_i
end
def to_s
value.to_s
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/newsfeed_day.rb | app/services/newsfeed_day.rb | class NewsfeedDay
attr_reader :title, :badges_added, :badges_removed,
:not_forked_projects_created, :failed_builds
def initialize(date)
@day = date.midnight
@title = @day.strftime("%Y-%m-%d")
@badges_added = Project.where('badge_in_readme = ? AND badge_in_readme_added_at > ? AND badge_in_readme_added_at <= ?', true, @day, @day+1.day).count
@badges_removed = Project.where('badge_in_readme = ? AND badge_in_readme_removed_at > ? AND badge_in_readme_removed_at <= ?', false, @day, @day+1.day).count
@not_forked_projects_created = Project.where('fork = ? AND created_at > ? AND created_at <= ?', false, @day, @day+1.day).count
@failed_builds = Build.where('status LIKE ? AND created_at > ? AND created_at <= ?', "failed:%", @day, @day+1.day).count
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/badge_markup.rb | app/services/badge_markup.rb | class BadgeMarkup < Struct.new(:project, :branch)
BASE_URL = "http://inch-ci.org"
IMAGE_FORMATS = [:svg, :png]
DEFAULT_IMAGE_FORMAT = IMAGE_FORMATS.first
IMAGE_STYLES = [nil, 'flat-square', 'shields']
def each(format = DEFAULT_IMAGE_FORMAT, style = nil, &block)
format_map(format, style).each(&block)
end
def image_formats
IMAGE_FORMATS
end
def image_path(format = DEFAULT_IMAGE_FORMAT, style = nil)
base = "#{page_path}.#{format}?branch=#{branch.name}"
base << "&style=#{style}" if style
base
end
def image_url(format = DEFAULT_IMAGE_FORMAT, style = nil)
"#{BASE_URL}#{image_path(format, style)}"
end
def styles
IMAGE_STYLES
end
private
def format_map(format, style = nil)
image = image_url(format, style)
link = page_url
alt = "Inline docs"
{
:image_url => "#{image}",
:md => "[](#{link})",
:textile => "!#{image}!:#{link}",
:rdoc => "{<img src=\"#{image}\" alt=\"#{alt}\" />}[#{link}]",
}
end
def page_path
"/#{project.service_name}/#{project.user_name}/#{project.repo_name}"
end
def page_url
"#{BASE_URL}#{page_path}"
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/build_history.rb | app/services/action/build_history.rb | require 'inch_ci/action'
module Action
class BuildHistory
include InchCI::Action
include Action::SetProjectAndBranch
exposes :project, :branch, :builds
exposes :running_builds, :scheduled_builds, :completed_builds
def initialize(params)
@language = params[:language]
set_project_and_branch(params)
set_builds
end
private
def set_builds
@builds = find_builds.map do |build|
BuildPresenter.new(build)
end
@scheduled_builds = @builds.select { |b| b.status == 'created' }
@running_builds = @builds.select { |b| b.status == 'running' }
@completed_builds = @builds.select { |b| !%w(created running).include?(b.status) }
end
def find_builds
filter_collection(collection)
end
def collection
if @project.nil?
InchCI::Store::FindBuilds.call()
else
InchCI::Store::FindBuildsInProject.call(@project)
end
end
def filter_collection(arel)
if @language
arel = arel.select { |b| b.branch.project.language.to_s.downcase == @language.downcase}
end
arel
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/set_project_and_branch.rb | app/services/action/set_project_and_branch.rb | require 'inch_ci/action'
module Action
module SetProjectAndBranch
def set_project_and_branch(params)
finder = InchCI::Action::FindProjectAndBranch.call(params)
unless finder.project.nil?
@project = ProjectPresenter.new(finder.project)
@branch = finder.branch
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/user/init_projects.rb | app/services/action/user/init_projects.rb | require 'inch_ci/action'
module Action
module User
class InitProjects
include InchCI::Action
exposes :user, :projects
ORIGIN = 'github_sync'
TRIGGER = 'first_signin'
def initialize(current_user, params)
@user = current_user.to_model
if @user.last_synced_projects_at.nil?
t1 = Time.now.to_f
InchCI::Store::UpdateLastProjectSync.call(@user)
if @user.provider == "github"
update_projects_via_github(@user)
end
find_ruby_projects.each do |project|
update_hook(project)
end
# we disable auto-building all projects for now
#.each do |project|
# build(project)
#end
t2 = Time.now.to_f
Rails.logger.info "InitProjects: user=#{@user.user_name} projects=#{@user.projects.count} delta=#{t2-t1}"
end
end
private
def update_projects_via_github(user)
github = InchCI::GitHubInfo.user(user.user_name)
repos = github.repos.map do |_repo|
repo = InchCI::GitHubInfo::Repo.new(_repo)
repo.fork? ? nil : repo
end.compact
find_not_existing_repos(repos).each do |repo|
project = create_project_and_branch(repo.url, repo.default_branch)
update_project_info(project, repo, user)
end
end
def find_not_existing_repos(repos)
all_uids = repos.map { |r| "github:#{r.name}" }
existing = ::Project.where(:uid => all_uids).pluck(:uid)
repos.reject { |r| existing.include?("github:#{r.name}") }
end
def create_project_and_branch(url, branch_name)
info = InchCI::RepoURL.new(url)
return if info.project_uid.nil?
project = InchCI::Store::CreateProject.call(info.project_uid, info.url, ORIGIN)
InchCI::Store::CreateBranch.call(project, branch_name)
project
end
def update_project_info(project, repo, user)
InchCI::Worker::Project::UpdateInfo.new.perform(project.uid, repo)
end
def find_ruby_projects
InchCI::Store::FindAllProjects.call(@user).select do |project|
project.language == 'Ruby'
end
end
def update_hook(project)
InchCI::Worker::Project::UpdateHook.enqueue project.uid, @user.github_access_token
end
def build(project)
InchCI::Worker::Project::Build.enqueue project.repo_url, project.default_branch.name, nil, TRIGGER
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/user/sync_projects.rb | app/services/action/user/sync_projects.rb | require 'inch_ci/action'
module Action
module User
class SyncProjects
include InchCI::Action
DEFAULT_TAB = Action::User::Show::DEFAULT_TAB
exposes :user, :projects, :languages, :active_tab
def initialize(current_user, params)
@user = UserPresenter.new(current_user)
@languages = Action::User::Show::LANGUAGES
@projects = retrieve_projects(current_user).map { |p| ProjectPresenter.new(p) }
@active_tab = params[:tab] || DEFAULT_TAB
end
private
def find_user(params)
InchCI::Store::FindUser.call(params[:service], params[:user])
end
def retrieve_projects(user)
InchCI::Worker::User::UpdateProjects.new.perform(user.id)
InchCI::Store::FindAllProjects.call(user).select(&:name)
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/user/signin.rb | app/services/action/user/signin.rb | require 'inch_ci/action'
module Action
module User
class Signin
include InchCI::Action
CLIENT_ID = InchCI::AccessToken[:github_client_id]
CLIENT_SECRET = InchCI::AccessToken[:github_secret]
exposes :user
def initialize(request)
@user = find_or_create_user(request.env["omniauth.auth"])
@new_user = @user.last_signin_at.nil?
@user.last_signin_at = Time.now
InchCI::Store::SaveUser.call(@user)
end
def new_user?
@new_user
end
private
def follows(user)
client = Octokit::Client.new(:access_token => user.github_access_token)
list = client.following(user.user_name)
list.map { |h| h['login'] }
end
def find_or_create_user(auth)
user = ::User.find_or_create_with_omniauth(auth)
user.github_access_token = auth["credentials"]["token"]
user.display_name = auth["info"]["name"]
user.user_name = auth["info"]["nickname"]
user.email = auth["info"]["email"]
user.follows = follows(user) if user.follows.nil?
user
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/user/welcome.rb | app/services/action/user/welcome.rb | require 'inch_ci/action'
module Action
module User
class Welcome
include InchCI::Action
LIMIT = 9
exposes :user, :followed_projects
def initialize(user)
@user = user
@followed_projects = find_projects(user).select(&:badge?)
count = @followed_projects.size
if count < LIMIT
@followed_projects.concat featured_projects(LIMIT-count)
else
@followed_projects = @followed_projects[0...LIMIT]
end
end
private
def find_projects(user)
sql = (['uid LIKE ?'] * user.follows.size).join(' OR ')
uids = user.follows.map { |name| "github:#{name}/%" }
present ::Project.includes(:default_branch)
.where(sql, *uids)
end
def featured_projects(limit)
present ::Project.includes(:default_branch)
.where(:id => featured_projects_uids(limit, :ruby))
end
def featured_projects_uids(limit, language)
FEATURED_PROJECT_UIDS[language][0...limit]
end
def present(projects)
projects.map { |p| ProjectPresenter.new(p) }
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/user/show.rb | app/services/action/user/show.rb | require 'inch_ci/action'
module Action
module User
class Show
include InchCI::Action
LANGUAGES = InchCI::Config::LANGUAGES
DEFAULT_TAB = LANGUAGES.first
exposes :user, :projects, :projects_without_badges, :languages,
:active_tab
def initialize(current_user, params)
if user = find_user(params)
@user = UserPresenter.new(user)
@languages = LANGUAGES
@projects = find_projects(@user) #.map { |p| ProjectPresenter.new(p) }
@projects_without_badges = @projects.select do |project|
project.language == 'Ruby' &&
project.default_branch.try(:latest_revision_id).nil?
end
@active_tab = params[:tab] || DEFAULT_TAB
else
raise "Not found: #{params}"
end
end
private
def find_user(params)
InchCI::Store::FindUser.call(params[:service], params[:user])
end
def find_projects(user)
InchCI::Store::FindAllProjects.call(user).select(&:name)
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/code_object/show.rb | app/services/action/code_object/show.rb | require 'inch_ci/action'
module Action
module CodeObject
class Show
include InchCI::Action
include Action::SetProjectAndBranch
exposes :project, :branch, :revision, :code_object
def initialize(params)
set_project_and_branch(params)
@revision = find_revision(@branch, params)
@code_object = find_code_object(params)
end
private
def find_code_object(params)
resource = InchCI::Store::FindCodeObject.call(params[:code_object])
CodeObjectPresenter.new(resource)
end
def find_revision(branch, params)
return if branch.nil?
if revision_uid = params[:revision]
InchCI::Store::FindRevision.call(@branch, revision_uid)
else
InchCI::Store::FindLatestRevision.call(@branch)
end
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/project/rebuild_via_hook.rb | app/services/action/project/rebuild_via_hook.rb | require 'inch_ci/action'
module Action
module Project
class RebuildViaHook
include InchCI::Action
TRIGGER = 'hook'
exposes :result
def initialize(params)
if params[:payload]
process_payload JSON[params[:payload]]
elsif params[:ref]
process_payload params
else
@result = "ERROR"
end
end
private
def enqueue_build(project, branch_name)
build = InchCI::Worker::Project::Build.enqueue(project.repo_url, branch_name, nil, TRIGGER)
end
def branch_name(payload)
payload['ref'] =~ /^refs\/heads\/(.+)$/ && $1
end
def process_payload(payload)
branch = EnsureProjectAndBranch.call(project_url(payload), branch_name(payload))
language = branch.project.language
if language.blank? || InchCI::Worker::Project.build_on_inch_ci?(language)
enqueue_build(branch.project, branch.name)
end
@result = "OK"
end
def project_url(payload)
if web_url = (payload['repository'] && payload['repository']['url'])
"#{web_url}.git"
end
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/project/update.rb | app/services/action/project/update.rb | require 'inch_ci/action'
module Action
module Project
class Update
include InchCI::Action
include Action::SetProjectAndBranch
exposes :project, :branch
# allow if user owns project or user is in project's org
def self.can_edit?(current_user, project)
organizations = current_user.organizations || []
project.user_name.downcase == current_user.user_name.downcase ||
organizations.map(&:downcase).include?(project.user_name.downcase)
end
def initialize(current_user, params)
set_project_and_branch(params)
if current_user && self.class.can_edit?(current_user, @project)
@project = @project.to_model
update_project(params[:project])
end
end
def success?
@project.valid?
end
private
def update_project(attributes)
@project.documentation_url = attributes[:documentation_url]
@project.language = attributes[:language]
InchCI::Store::SaveProject.call(@project)
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/project/rebuild.rb | app/services/action/project/rebuild.rb | require 'inch_ci/action'
module Action
module Project
class Rebuild
include InchCI::Action
include Action::SetProjectAndBranch
exposes :project, :branch, :build
def initialize(params)
set_project_and_branch(params)
if @project && @branch
# maybe we should check of there is a build running for this branch?
@build = InchCI::Worker::Project::Build.enqueue(@project.repo_url, @branch.name)
end
end
def build_id
@build.id
end
def success?
!@build.nil?
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/project/activate_hook.rb | app/services/action/project/activate_hook.rb | require 'inch_ci/action'
module Action
module Project
class ActivateHook
include InchCI::Action
include Action::SetProjectAndBranch
TRIGGER = 'activate_hook'
exposes :project
def initialize(user, params)
set_project_and_branch(params)
if user_access_token = user.github_access_token
process_via_github(@project.to_model, user_access_token)
if @project.to_model.builds.count == 0
build(project)
end
else
raise "Need access token!"
end
end
def success?
!@project.github_hook_id.nil?
end
private
def build(project)
InchCI::Worker::Project::Build.enqueue project.repo_url, project.default_branch.name, nil, TRIGGER
end
def process_via_github(project, user_access_token)
client = Octokit::Client.new(access_token: user_access_token)
if project.github_hook_id
response = client.edit_hook(project.name, project.github_hook_id,
hook_service, hook_url_config, hook_activate_options)
else
hook = client.create_hook(project.name, hook_service,
hook_url_config, hook_create_options)
project.github_hook_id = hook.id
end
project.github_hook_active = true
InchCI::Store::SaveProject.call(project)
end
module HookConfig
HOOK_URL = 'https://inch-ci.org/rebuild'
def hook_service
'web'
end
def hook_url_config
{url: HOOK_URL, content_type: 'json'}
end
def hook_create_options
{events: ['push'], active: true}
end
def hook_activate_options
{active: true}
end
def hook_deactivate_options
{active: false}
end
end
include HookConfig
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/project/deactivate_hook.rb | app/services/action/project/deactivate_hook.rb | require 'inch_ci/action'
module Action
module Project
class DeactivateHook
include InchCI::Action
include Action::SetProjectAndBranch
exposes :project
def initialize(user, params)
set_project_and_branch(params)
if user_access_token = user.github_access_token
process_via_github(@project.to_model, user_access_token)
else
raise "Need access token!"
end
end
def success?
!@success.nil?
end
private
def process_via_github(project, user_access_token)
client = Octokit::Client.new(access_token: user_access_token)
if project.github_hook_id
response = client.edit_hook(project.name, project.github_hook_id,
hook_service, hook_url_config, hook_deactivate_options)
if response.active == false
project.github_hook_active = false
InchCI::Store::SaveProject.call(project)
@success = true
end
end
end
include Action::Project::ActivateHook::HookConfig
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/project/suggestions.rb | app/services/action/project/suggestions.rb | module Action
module Project
class Suggestions < Show
FILE_COUNT = 5
GRADES_TO_DISPLAY = %w(B C U)
GRADE_WEIGHTS = [0.2, 0.4, 0.4]
MIN_PRIORITY = 0
exposes :project, :branch, :revision, :collection, :suggestion_count
exposes :suggestions, :files
def initialize(params)
super
if @code_objects
suggested = filter_suggested_code_objects(@code_objects)
@suggestions = InchCI::GradeListCollection.new(suggested)
files = suggested.map(&:filename)
@files = sort_files_by_frequency(files)[0...FILE_COUNT]
end
end
private
def sort_files_by_frequency(filenames)
filenames.uniq.map do |f|
count = filenames.select { |fn| fn == f }.size
[count, f]
end.sort.reverse.map(&:last)
end
def filter_suggested_code_objects(code_objects)
graded_list = GRADES_TO_DISPLAY.map do |grade|
code_objects.select do |code_object|
code_object.grade == grade &&
code_object.priority >= MIN_PRIORITY
end
end
weighted_list = ::Inch::Utils::WeightedList.new(graded_list, object_list_counts)
list = ::Inch::Codebase::Objects.sort_by_priority(weighted_list.to_a.flatten)
list = list[0...object_count] if list.size > MAX_SUGGESTIONS
list
end
# @return [Array<Fixnum>]
# how many objects of each grade should be displayed in the output
def object_list_counts
GRADE_WEIGHTS.map { |w| w * MAX_SUGGESTIONS }
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/project/update_info.rb | app/services/action/project/update_info.rb | require 'inch_ci/action'
module Action
module Project
class UpdateInfo
include InchCI::Action
include Action::SetProjectAndBranch
exposes :project, :branch
def initialize(current_user, params)
set_project_and_branch(params)
update_project
if current_user && @project.user_name == current_user.user_name
update_hook(current_user.github_access_token)
end
end
private
def update_project
worker = InchCI::Worker::Project::UpdateInfo.new
worker.perform(@project.uid)
end
def update_hook(user_access_token)
worker = InchCI::Worker::Project::UpdateHook.new
worker.perform(@project.uid, user_access_token)
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/project/badge.rb | app/services/action/project/badge.rb | require 'inch_ci/action'
module Action
module Project
class Badge
include InchCI::Action
include Action::SetProjectAndBranch
exposes :project, :branch, :badge_filename, :content_type
def initialize(params)
set_project_and_branch(params)
if !@project
create_project_and_branch(params)
if @project && @branch
create_empty_badge
enqueue_build
end
end
if @project && @branch
@badge = InchCI::BadgeRequest.new(@project.service_name, @project.user_name, @project.repo_name, @branch.name)
format = 'svg' # we only serve SVG badges
style = params[:style]
@badge_filename = @badge.local_filename(format, style)
@content_type = content_types[format]
if !File.exist?(@badge_filename)
@badge_filename = Rails.root.join('app/assets/images/transparent.png')
@content_type = content_types['png']
end
end
end
def success?
!@badge.nil?
end
private
TRIGGER = 'manual'
ORIGIN = :badge_request
def content_types
{
'png' => 'image/png',
'svg' => 'image/svg+xml'
}
end
def create_empty_badge
InchCI::Badge.create(@project, @branch, [0,0,0,0])
end
def create_project_and_branch(url_or_params, _branch_name = nil)
branch_name = url_or_params.is_a?(Hash) ? url_or_params[:branch] : nil
branch_name ||= _branch_name
if @branch = InchCI::Action::EnsureProjectAndBranch.call(url_or_params, branch_name, ORIGIN)
@project = @branch.project
@branch
end
end
def enqueue_build
InchCI::Worker::Project::Build.enqueue(@project.repo_url, @branch.name, nil, TRIGGER)
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/project/create.rb | app/services/action/project/create.rb | require 'inch_ci/action'
module Action
module Project
class Create
include InchCI::Action
exposes :project
def initialize(params, origin = nil)
return unless params[:repo_url].present?
info = InchCI::RepoURL.new(params[:repo_url])
if info.repo_url.nil?
info = InchCI::RepoURL.new("https://github.com/#{params[:repo_url]}")
end
if @project = InchCI::Store::EnsureProject.call(info.repo_url, origin)
if @project = update_project(@project)
if branch = InchCI::Store::FindDefaultBranch.call(@project)
create_build_if_possible(@project, branch)
end
end
end
end
def build_id
@build.id if @build
end
def success?
!@project.nil? && !@project.name.nil?
end
private
def create_build_if_possible(project, branch)
if InchCI::Worker::Project.build_on_inch_ci?(project.language)
@build = InchCI::Worker::Project::Build.enqueue(project.repo_url, branch.name)
end
end
def update_project(project)
worker = InchCI::Worker::Project::UpdateInfo.new
worker.perform(project.uid)
InchCI::Store::FindProject.call(project.uid)
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/project/history.rb | app/services/action/project/history.rb | require 'inch_ci/action'
require 'inch_ci/grade_list_collection'
module Action
module Project
class History < Show
include InchCI::Action
include Action::SetProjectAndBranch
exposes :project, :branch, :revision, :collection, :suggestion_count
exposes :builds, :diffs, :code_object_map
def initialize(params)
super
if @revision
@builds = present(find_builds, BuildPresenter)
@diffs = @builds.map(&:revision_diff).compact
@code_object_map = create_code_object_map(@diffs)
end
end
private
def create_code_object_map(revision_diffs)
code_object_map = {}
code_object_ids = revision_diffs.flat_map do |rev_diff|
rev_diff.to_model.code_object_diffs.flat_map do |obj_diff|
[obj_diff.before_object_id, obj_diff.after_object_id]
end
end
::CodeObject.where(:id => code_object_ids).each do |code_object|
code_object_map[code_object.id] = CodeObjectPresenter.new(code_object)
end
code_object_map
end
def find_builds
InchCI::Store::FindBuildsInBranch.call(@branch)
end
def present(list, presenter_class)
list.map { |diff| presenter_class.new(diff) }
end
def limit(list, max_count = 50)
count = 0
result = []
list.each do |rev_diff|
count += 1 if rev_diff.change_count > 0
result << rev_diff
if count >= max_count
return result
end
end
result
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/project/show.rb | app/services/action/project/show.rb | require 'inch_ci/action'
require 'inch_ci/grade_list_collection'
module Action
module Project
class Show
include InchCI::Action
include Action::SetProjectAndBranch
MAX_SUGGESTIONS = 20
exposes :project, :branch, :revision, :user, :code_objects,
:collection, :suggestion_count, :pending_build
def initialize(params)
set_project_and_branch(params)
@build = find_pending_build(params)
if revision = find_revision(@branch, params)
@user = project.user
@revision = RevisionPresenter.new(revision)
@code_objects = find_code_objects(revision)
@collection = create_collection(@code_objects)
@suggestion_count = @code_objects.select do |code_object|
code_object.grade != 'A'
end.size
if @suggestion_count > MAX_SUGGESTIONS
@suggestion_count = "#{MAX_SUGGESTIONS}+"
end
end
end
private
def find_code_objects(revision)
return [] if revision.nil?
list = InchCI::Store::FindRelevantCodeObjects.call(revision)
present_code_objects(list)
end
def create_collection(code_objects)
InchCI::GradeListCollection.new(code_objects)
end
def find_pending_build(params)
if uid = params[:pending_build]
build = InchCI::Store::FindBuild.call(uid)
unless build.finished_at
@pending_build = build
end
end
end
def find_revision(branch, params)
return if branch.nil?
if revision_uid = params[:revision]
InchCI::Store::FindRevision.call(@branch, revision_uid)
else
InchCI::Store::FindLatestRevision.call(@branch)
end
end
def present_code_objects(code_objects)
code_objects.map { |o| CodeObjectPresenter.new(o) }
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/build/show.rb | app/services/action/build/show.rb | require 'inch_ci/action'
module Action
module Build
class Show
include InchCI::Action
exposes :build, :code_object_map, :filename, :dump
def initialize(params, load_dump: false, load_diff: false)
if uid = params[:id]
@build = BuildPresenter.new(InchCI::Store::FindBuild.call(uid))
if load_diff && @build.revision_diff
@code_object_map = create_code_object_map([@build.revision_diff])
end
if load_dump
load_dump_if_present
end
end
end
private
def create_code_object_map(revision_diffs)
code_object_map = {}
code_object_ids = revision_diffs.flat_map do |rev_diff|
rev_diff.to_model.code_object_diffs.flat_map do |obj_diff|
[obj_diff.before_object_id, obj_diff.after_object_id]
end
end
::CodeObject.where(:id => code_object_ids).each do |code_object|
code_object_map[code_object.id] = CodeObjectPresenter.new(code_object)
end
code_object_map
end
def load_dump_if_present
@filename = Rails.root.join('dumps', 'builds', "build-#{@build.id}.json")
@dump = File.read(@filename) if File.exist?(@filename)
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/cli/list_dumps.rb | app/services/action/cli/list_dumps.rb | require 'inch_ci/action'
module Action
module CLI
class ListDumps
include InchCI::Action
LANGUAGES = %w(elixir nodejs)
exposes :languages, :language, :filenames, :dates
def initialize(params)
@languages = LANGUAGES
if @language = params[:language]
glob = File.join(dump_dir, '**/*.json')
@filenames = filter_by_language(basenames_by_glob(glob))
@dates = {}
@filenames.each do |filename|
date = filename =~ /\/(\d+)\// && $1
unless date.nil?
@dates[date] ||= []
@dates[date] << filename
end
end
end
end
private
def dump_dir
Rails.root.join('dumps', 'cli').to_s
end
def basenames_by_glob(glob)
Dir[glob].sort.reverse.map do |f|
f.gsub(dump_dir+'/', '').gsub(/\.json$/, '')
end
end
def filter_by_language(filenames)
filenames.select do |f|
f.starts_with?(@language)
end
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/services/action/cli/get_dump.rb | app/services/action/cli/get_dump.rb | require 'inch_ci/action'
module Action
module CLI
class GetDump
include InchCI::Action
exposes :filename, :json, :out
def initialize(params)
if @filename = params[:filename]
@json = JSON[ File.read( filename_from_params(@filename, :json) ) ]
@out = terminal File.read( filename_from_params(@filename, :out) )
end
end
private
def filename_from_params(basename, ext)
filename = File.join(dump_dir, basename.gsub(/[\.\~]/, '') + '.' + ext.to_s)
filename if File.exists?(filename)
end
def dump_dir
Rails.root.join('dumps', 'cli').to_s
end
def terminal(str)
str.uncolored.strip
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/presenters/revision_diff_presenter.rb | app/presenters/revision_diff_presenter.rb | class RevisionDiffPresenter < BasePresenter
def code_object(id)
@code_objects ||= {}
CodeObjectPresenter.new(@code_objects[id] || CodeObject.find(id))
end
def revision
@revision ||= RevisionPresenter.new(@resource.after_revision)
end
def change_count
@change_count ||= [*changes.values].flatten.size
end
def changes
@changes ||= begin
map = {'added' => [], 'improved' => [], 'degraded' => [], 'removed' => [], }
@resource.code_object_diffs.each do |diff|
map[diff.change] ||= []
map[diff.change] << diff
end
map
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/presenters/base_presenter.rb | app/presenters/base_presenter.rb | # A BasePresenter object represents a +resource+ (i.e. data object) in the
# view layer of application delivery.
#
# == Creation
#
# You create a Presenter object by subclassing BasePresenter:
#
# class ProjectPresenter < BasePresenter
# end
#
# The constructor takes the +resource+ as its single parameter:
#
# p = Project.new(:name => "Test project")
# presenter = ProjectPresenter.new(p)
#
# This presenter is not yet capable of anything:
#
# presenter.name # => NoMethodError: ...
#
# You can easily create delegates to existing attributes of the represented +resource+:
#
# class ProjectPresenter < BasePresenter
# def_delegators :project, :name, :description
# end
#
# This creates a Presenter class for Project objects and delegates the
# +name+ and +description+ attributes to the original +project+ object.
#
# presenter.name # => "Test project"
#
# == Exposing presenters through the controller
#
# To use presenter objects in the view layer, we can expose them through
# the controller. This works by defining which instance variables should be
# available as presenter objects in the view layer.
#
# class ProjectController < ApplicationController
# expose_presenters :project, :projects
# end
#
# This defines two (helper-)methods +project+ and +projects+, that look
# up +@project+ and +@projects+ and convert them to presenter objects.
#
# Now, the following view code works:
#
# <h1><%= project.name %></h1>
#
#
# == Adding custom methods
#
# Adding custom methods enables you to represent information in a
# context-sensitive way:
#
# class ProjectPresenter < BasePresenter
# def_delegators :project, :name, :description
#
# def label
# if project.active?
# project.name
# else
# "[OLD] " + project.name
# end
# end
# end
#
# presenter.label # => "Test project"
# presenter.active = false
# presenter.label # => "[OLD] Test project"
#
# == Using presenters for associations
#
# To illustrate this suppose we have a model Station that is associated
# with a Project.
#
# class StationPresenter
# def_delegators :branch, :project
# end
#
# p = BranchPresenter.new(...).project # => Project
# p.label # => NoMethodError: ...
#
# This is because the project method is delegated to the +resource+ and
# returns such a data object itself. This is were use_presenters helps:
#
# class BranchPresenter
# use_presenters :project
# end
#
# p = BranchPresenter.new(...).project # => ProjectPresenter
# p.label # => "[OLD] Test project"
#
class BasePresenter
extend Forwardable
def_delegators :@resource, :id, :new_record?, :valid?, :to_param, :to_json, :to_xml, :to_yaml
# @param resource [ActiveRecord::Base]
def initialize(resource)
@resource = resource
end
# Returns the actual resource object the presenter is representing.
#
# Example:
#
# p = Project.new
# ProjectPresenter.new(p).to_model # => p
#
# In this case to_model returns the original Project object.
#
# This is called by rails helper methods (e.g. 'dom_id')
#
# @return [ActiveRecord::Base,Object] the presented data object
def to_model
@resource
end
class << self
# Defines a reader method named according to the presenter that returns
# the presenters resource, so can refer to your data object in a natural
# way.
#
# Example:
#
# class ProjectPresenter < BasePresenter
# def label
# if project.active?
# project.name
# else
# "[OLD] " + project.name
# end
# end
# end
#
# @return [void]
def inherited(subclass)
name = subclass.to_s.gsub(/Presenter$/, '').split("::").last.underscore
subclass.__send__(:define_method, name) { @resource }
end
# Defines associations which should return a Presenter object rather
# than an ActiveRecord object.
#
# Example:
#
# class StationPresenter
# def_delegators :station, :project
# end
#
# StationPresenter.new(...).project # => Project
#
# class StationPresenter
# use_presenters :project
# end
#
# StationPresenter.new(...).project # => ProjectPresenter
#
# @return [void]
def use_presenters(*names)
names.each do |name|
define_method(name) do
if var = instance_variable_get("@#{name}")
var
else
var = @resource.__send__(name)
if var
if var.respond_to?(:map)
instance_variable_set "@#{name}", var.map(&:to_presenter)
else
instance_variable_set "@#{name}", var.to_presenter
end
end
end
end
end
end
end
# Contains methods that can be included into Rails controllers.
module ControllerMethods
extend ActiveSupport::Concern
module ClassMethods
# Exposes data objects to the view layer via their designated presenters.
#
# Example:
#
# class StationController < ApplicationController
# expose_presenters :station, :stations
# end
#
# This defines two (helper-)methods +station+ and +stations+, that look
# up +@station+ and +@stations+ and convert them to presenter objects.
#
# @param names [Array<String, Symbol>] names of the to-be-created methods
# @return [void]
def expose_presenters(*names)
if names.empty?
class_name = to_s.split('::').last.gsub(/Controller$/, '')
collection_name = class_name.underscore
resource_name = collection_name.singularize
names = [resource_name, collection_name]
end
names.each do |name|
define_method name do
cached = instance_variable_get("@#{name}__presenter")
if cached
cached
else
obj = instance_variable_get("@#{name}")
return if obj.nil?
cached = if obj.is_a?(Array) || obj.is_a?(ActiveRecord::Relation)
obj.map(&:to_presenter)
else
obj.to_presenter
end
instance_variable_set("@#{name}__presenter", cached)
end
end
helper_method name
end
end
end
end
end
class ActiveRecord::Base
def to_presenter
Module.const_get(self.class.to_s+'Presenter').new(self)
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/presenters/code_object_presenter.rb | app/presenters/code_object_presenter.rb | class CodeObjectPresenter < BasePresenter
def_delegators :code_object, :fullname, :score, :grade, :priority, :docstring
def_delegators :code_object, :project, :branch
# TODO: use_presenters :project, :branch
use_presenters :code_object_roles
def bad_code_object_roles
code_object_roles.select(&:bad?).sort_by do |role|
[role.potential_score.to_i, role.name]
end.reverse
end
def filename
location.first
end
def line_no
location.last
end
def name
fullname.split('::').last.split('#').last
end
def priority_symbol(priority = @resource.priority)
::Inch::Evaluation::PriorityRange.all.each do |range|
if range.include?(priority)
return range.to_sym
end
end
end
def type
@resource.type.split('::').last.downcase
end
private
def location
@__location ||= code_object.to_model.location.to_s.partition(':')
end
end | ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/presenters/code_object_role_presenter.rb | app/presenters/code_object_role_presenter.rb | class CodeObjectRolePresenter < BasePresenter
def_delegators :code_object_role, :ref_name, :priority, :score, :potential_score, :min_score, :max_score
def bad?
potential_score.to_i > 0
end
def name
code_object_role.code_object_role_name.name
end
def to_desc(object = nil)
args = {
:object_type => object && object.type,
:ref_name => ref_name || object && object.name
}
I18n.t(to_i18n_key, args)
end
def to_i18n_key
to_partial.gsub('/', '.')
.gsub(/\.inch\.language\.([^\.]+)\.evaluation\.role\./, '.\1.')
end
def to_partial
"shared/code_object_roles/#{name.underscore}"
end
end | ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/presenters/user_presenter.rb | app/presenters/user_presenter.rb | class UserPresenter < BasePresenter
def_delegators :user, :display_name, :user_name, :email, :provider, :follows,
:last_synced_projects_at, :last_signin_at,
:github_access_token, :organizations
use_presenters :projects
def github_url
"https://github.com/#{user_name}"
end
def name
display_name
end
def service_name
provider
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/presenters/project_presenter.rb | app/presenters/project_presenter.rb | class ProjectPresenter < BasePresenter
def_delegators :project, :uid, :name, :description
def_delegators :project, :homepage_url, :source_code_url, :repo_url, :documentation_url
def_delegators :project, :language, :origin
def_delegators :project, :github_hook_id, :github_hook_active
def_delegators :project, :service_name, :user_name, :repo_name
def_delegators :project, :created_at, :updated_at
def_delegators :project, :default_branch, :branches, :builds, :user
def badge?
default_branch && !default_branch.try(:latest_revision_id).nil?
end
def build_on_inch_ci?
InchCI::Worker::Project.build_on_inch_ci?(project.language)
end
def build_on_travis?
!build_on_inch_ci?
end
def hooked?
!project.github_hook_id.nil? && project.github_hook_active
end
def language?(language)
project.language.to_s.downcase == language.to_s.downcase
end
def last_build
builds.first.to_presenter
end
def name_without_owner
name.to_s.split('/').last
end
def unsupported_language?
!InchCI::Config::LANGUAGES.include?(project.language.to_s)
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/presenters/revision_presenter.rb | app/presenters/revision_presenter.rb | class RevisionPresenter < BasePresenter
def_delegators :revision, :diff, :tag_uid, :badge_in_readme?
def_delegators :revision, :author_name, :author_email, :authored_at, :message
def_delegators :revision, :branch, :project
use_presenters :builds, :code_objects
def uid(short = true)
short ? revision.uid[0..7] : revision.uid
end
def tag_uid(short = true, count = 10)
return unless revision.tag_uid
if short && revision.tag_uid.size > 10
revision.tag_uid[0...count] + '...'
else
revision.tag_uid
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/presenters/build_presenter.rb | app/presenters/build_presenter.rb | class BuildPresenter < BasePresenter
def_delegators :build, :status, :trigger, :started_at, :finished_at
def_delegators :build, :branch, :revision, :number, :stderr
use_presenters :revision, :revision_diff
def duplicate?
status == 'duplicate'
end
def finished?
status != 'created' && status != 'running'
end
def duration
finished_at.to_i - started_at.to_i
end
def no_sources_found?
!!(stderr.to_s =~ /no sources found/i)
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/helpers/projects_helper.rb | app/helpers/projects_helper.rb | module ProjectsHelper
def badge_markup
@badge_markup ||= BadgeMarkup.new(@project, @branch)
end
def escape_markdown(str)
str.to_s.gsub('_', '\_')
end
def tweet_url(project = nil)
url = project ? project_url(project) : root_url
text = project ? t("shared.twitter_text", :project_language => project.language, :project_name => project.name) : t("shared.twitter_text_wo_project")
"https://twitter.com/share?url=#{url}&text=#{text} &via=InchCI"
end
def github_issue_url(options = {})
title = ''
if project = options[:project]
p_url = project_url(project)
body = "\n\n---\nRe: [#{project.name}](#{p_url})"
if code_object = options[:code_object]
c_url = code_object_url(project, options[:branch].name, options[:revision].uid[0..7], :code_object => code_object)
body = "\n\n---\nRe: [#{code_object.grade}] [#{code_object.fullname}](#{c_url}) in [#{project.name}](#{p_url})"
end
end
"https://github.com/inch-ci/inch_ci-web/issues/new?title=#{URI.escape(title)}&body=#{URI.escape(body)}"
end
def link_to_build_history(project)
url = project_build_history_path(project)
link = link_to(t("projects.topbar.info.builds_link"), url)
t("projects.topbar.info.builds_all", :link => link).html_safe
end
def link_to_edit_project(project)
url = edit_project_path(project)
link = link_to(t("projects.topbar.info.edit_link"), url)
t("projects.topbar.info.edit_all", :link => link).html_safe
end
def link_to_project(project, text = project.name)
link_to text, project_path(project)
end
def link_to_branch(branch)
project = branch.project
link_to truncate(branch.name), project_path(project, branch.name)
end
def link_to_revision(revision)
branch = revision.branch
project = branch.project
link_to revision.uid[0..7], project_path(project, branch.name, revision.uid)
end
def link_to_subnavi(action, path, i18n_opts = {})
text = t("projects.subnavi.#{action}", i18n_opts)
classes = %w(btn btn-default)
classes << 'active' if controller.action_name == action.to_s
link_to text.html_safe, path, :class => classes
end
def link_to_with_hostname(url, options)
hostname = URI.parse(url).host.gsub(/^www\./, '')
link_to hostname, url, options
end
def promo_hint
<<-PROMO
<!--
Hi there,
I want to propose to add this badge to the README to show off inline-documentation: [](http://inch-ci.org/github/#{@project.name})
The badge links to [Inch CI](http://inch-ci.org) and shows an evaluation by [InchJS](http://trivelop.de/inchjs), a project that tries to raise the visibility of inline-docs. Besides testing and other coverage, documenting your code is often neglected although it is a very engaging part of Open Source.
So far over 500 **Ruby** projects are sporting these badges to raise awareness for the importance of inline-docs and to show potential contributors that they can expect a certain level of code documentation when they dive into your project's code and motivate them to eventually document their own. I would really like to do the same for the **JavaScript** community and roll out support for JS over the coming weeks (early adopters are [forever](https://github.com/foreverjs/forever), [node-sass](https://github.com/sass/node-sass) and [when](https://github.com/cujojs/when)).
Although this is "only" a passion project, I really would like to hear your thoughts, critique and suggestions. Your status page is http://inch-ci.org/github/#{@project.name}
What do you think?
-->
PROMO
end
def show_rebuild_link?
@project.build_on_inch_ci?
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/helpers/code_objects_helper.rb | app/helpers/code_objects_helper.rb | module CodeObjectsHelper
def link_to_code_object(revision, code_object)
branch = revision.branch
project = branch.project
path = code_object_path(project, branch.name, revision.uid, :code_object => code_object)
link_to code_object.fullname, path, :"data-code_object-id" => code_object.id, :remote => true, :method => :get
end
def url_on_github(filename, line_no = nil)
base = "https://github.com/#{@project.user_name}/#{@project.repo_name}/blob/#{@revision.uid}/#{filename}"
line_no ? "#{base}#L#{line_no}" : base
end
def show_code_object_location?(project = @project)
%w(javascript nodejs).include?(project.language.to_s.downcase)
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/helpers/users_helper.rb | app/helpers/users_helper.rb | module UsersHelper
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/helpers/gossip_helper.rb | app/helpers/gossip_helper.rb | module GossipHelper
def gossip_active?
InchCI::Gossip::GOSSIP_ACTIVE
end
def gossip_server
return unless gossip_active?
InchCI::Gossip::GOSSIP_HOST
end
def gossip_room
return unless gossip_active?
if @project
"projects:#{@project.uid}"
else
@gossip_room # "projects:lobby"
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/helpers/application_helper.rb | app/helpers/application_helper.rb | module ApplicationHelper
def icon(key, options = {})
opts = options.merge(:class => "fa fa-#{key} #{options[:class]}".strip)
content_tag(:i, "", opts).html_safe
end
def markdown(text)
renderer = Redcarpet::Markdown.new(TargetBlankRenderer,
:autolink => true, :space_after_headers => true)
renderer.render(text).html_safe
end
end
class TargetBlankRenderer < Redcarpet::Render::HTML
def initialize(extensions = {})
super extensions.merge(:link_attributes => {:target => "_blank"})
end
end | ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/helpers/help_helper.rb | app/helpers/help_helper.rb | module HelpHelper
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/helpers/builds_helper.rb | app/helpers/builds_helper.rb | module BuildsHelper
def back_button(path)
link_to icon('arrow-left') + ' ' + t("shared.back_link"), path, :class => "btn btn-default btn-cancel"
end
def build_css_class(build)
{
'created' => '',
'running' => :info,
'success' => :success,
'duplicate' => :warning,
'cancelled' => :cancelled,
}[build.status] || :danger
end
def build_status_icon(build)
key = build_status_icon_map[build.status]
title = t("builds.status.#{build.status}", :default => build.status)
icon(key || :question, :title => title)
end
def build_status_icon_map
{
'created' => :"circle-o",
'cancelled' => :"arrow-up",
'duplicate' => :"check-square",
'running' => :"spinner fa-pulse",
'success' => :check,
'failed:retriever' => :exclamation,
}
end
def build_trigger_icon(build)
key = build_trigger_icon_map[build.trigger]
icon(key || :question, :title => build.trigger)
end
def build_trigger_icon_map
{
'cron' => :"clock-o",
'hook' => :git,
'manual' => :user,
'tag_build' => :tags,
'shell' => :terminal,
'travis' => :"cloud-upload",
}
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/helpers/admin/overview_helper.rb | app/helpers/admin/overview_helper.rb | module Admin::OverviewHelper
def created_at_classes(object)
today = Time.now.utc.midnight
created = object.created_at.midnight
[
created == today ? 'today' : nil,
created == today - 1.day ? 'yesterday' : nil,
]
end
def link_to_user_projects(user, language = nil)
projects = user.projects
if language
projects = projects.where(:language => language)
end
link_to projects.size, admin_projects_path(:service => user.provider, :user => user.user_name, :language => language)
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/revisions_controller.rb | app/controllers/revisions_controller.rb | class RevisionsController < ApplicationController
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/page_controller.rb | app/controllers/page_controller.rb | class PageController < ApplicationController
layout 'application'
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/help_controller.rb | app/controllers/help_controller.rb | class HelpController < ApplicationController
layout 'application'
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/builds_controller.rb | app/controllers/builds_controller.rb | require 'inch_ci/controller'
class BuildsController < ApplicationController
include InchCI::Controller
layout 'application'
def index
view = Action::BuildHistory.new(params)
expose view
end
def history_show
view = Action::Build::Show.new(params, load_diff: true)
expose view
end
def show
view = Action::Build::Show.new(params)
expose view
render :json => @build
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/projects_controller.rb | app/controllers/projects_controller.rb | require 'inch_ci/controller'
require 'inch_ci/badge'
class ProjectsController < ApplicationController
include InchCI::Controller
layout 'application'
skip_before_action :verify_authenticity_token, :only => [:rebuild_via_hook]
def badge
action = Action::Project::Badge.new(params)
if action.success?
response.headers['Expires'] = Time.now.to_s
response.headers['Pragma'] = 'no-cache'
response.headers['Cache-Control'] = 'no-cache'
send_file action.badge_filename, :content_type => action.content_type,
:disposition => 'inline'
else
render :text => "Project or branch not found.", :layout => false, :status => 404
end
end
def create
action = Action::Project::Create.new(params, :homepage)
if action.success?
redirect_to project_url(action.project, :pending_build => action.build_id)
else
expose action
flash[:error] = t("projects.create.url_not_found")
render :template => "page/welcome"
end
end
def create_hook
action = Action::Project::ActivateHook.new(current_user, params)
expose action
if !action.success?
flash[:error] = "Could not create hook for #{@project.name}"
end
redirect_to user_url(current_user, :tab => @project.language)
end
def edit
process_project_action Action::Project::Show
end
def update
action = Action::Project::Update.new(current_user, params)
if action.success?
redirect_to project_url(action.project)
else
redirect_to edit_project_url(action.project)
end
end
def history
process_project_action Action::Project::History
end
def rebuild
action = Action::Project::Rebuild.new(params)
if action.success?
redirect_to project_url(action.project, action.branch.name, :pending_build => action.build_id)
else
render :text => "Project not found.", :layout => false, :status => 404
end
end
def rebuild_via_hook
action = Action::Project::RebuildViaHook.new(params)
render :text => action.result
end
def remove_hook
action = Action::Project::DeactivateHook.new(current_user, params)
expose action
if !action.success?
flash[:error] = "Could not remove hook for #{@project.name}"
end
redirect_to user_url(current_user, :tab => @project.language)
end
def suggestions
process_project_action Action::Project::Suggestions
end
def update_info
action = Action::Project::UpdateInfo.new(current_user, params)
redirect_to project_url(action.project, action.branch.name)
end
def show
process_project_action Action::Project::Show
end
private
def determine_layout
case action_name
when 'create'
'cover'
else
'page'
end
end
def process_project_action(action_class)
action = action_class.new(params)
expose action
if action.project.nil?
render :text => "Project not found.", :layout => true, :status => 404
else
if action.branch.nil?
render :text => "Branch not found.", :layout => true, :status => 404
end
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/code_object_roles_controller.rb | app/controllers/code_object_roles_controller.rb | class CodeObjectRolesController < ApplicationController
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/users_controller.rb | app/controllers/users_controller.rb | require 'inch_ci/controller'
class UsersController < ApplicationController
include InchCI::Controller
before_action :require_login
layout 'application'
def init_projects
action = Action::User::InitProjects.new(current_user, params)
expose action
respond_to do |format|
format.js
end
end
def sync_projects
action = Action::User::SyncProjects.new(current_user, params)
expose action
respond_to do |format|
format.html { redirect_to user_url(action.user) }
format.js
end
end
def show
action = Action::User::Show.new(current_user, params)
expose action
end
def welcome
action = Action::User::Welcome.new(current_user)
expose action
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/code_objects_controller.rb | app/controllers/code_objects_controller.rb | require 'inch_ci/controller'
class CodeObjectsController < ApplicationController
include InchCI::Controller
def show
view = Action::CodeObject::Show.new(params)
expose view
if view.code_object.nil?
render :text => "CodeObject not found.", :layout => true, :status => 404
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/branches_controller.rb | app/controllers/branches_controller.rb | class BranchesController < ApplicationController
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/sessions_controller.rb | app/controllers/sessions_controller.rb | class SessionsController < ApplicationController
def create
action = Action::User::Signin.new(request)
self.current_user = action.user
redirect_to action.new_user? ? welcome_url : user_url(current_user)
end
def destroy
session[:user_id] = nil
redirect_to root_url, :notice => "Signed out!"
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/application_controller.rb | app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
private
def featured_projects(language)
@featured_projects ||= {}
@featured_projects[language] ||= FEATURED_PROJECT_UIDS[language].map do |uid|
InchCI::Store::FindProject.call(uid)
end.compact
end
helper_method :featured_projects
def code_object_path(*args)
project_path(*args).merge(:controller => 'code_objects', :action => 'show')
end
helper_method :code_object_path
def code_object_url(*args)
url_for code_object_path(*args)
end
helper_method :code_object_url
def project_path(project, *args)
options = args.extract_options!
branch_name = args.shift
revision_uid = args.shift
hash = {
:controller => '/projects',
:action => 'show',
:service => project.service_name,
:user => project.user_name,
:repo => project.repo_name,
:branch => branch_name,
:revision => revision_uid,
}
hash.merge(options)
end
helper_method :project_path
def edit_project_path(*args)
project_path(*args).merge(:action => 'edit')
end
helper_method :edit_project_path
def project_build_history_path(*args)
project_path(*args).merge(:controller => 'builds', :action => 'index')
end
helper_method :project_build_history_path
def project_history_path(*args)
project_path(*args).merge(:action => 'history')
end
helper_method :project_history_path
def project_history_url(*args)
url_for project_path(*args).merge(:action => 'history', :protocol => 'http')
end
helper_method :project_history_url
def project_suggestions_path(*args)
project_path(*args).merge(:action => 'suggestions')
end
helper_method :project_suggestions_path
def project_rebuild_path(*args)
project_path(*args).merge(:action => 'rebuild')
end
helper_method :project_rebuild_path
def project_update_info_path(*args)
project_path(*args).merge(:action => 'update_info')
end
helper_method :project_update_info_path
def project_url(*args)
url_for project_path(*args)
end
helper_method :project_url
def signin_path(provider = :github)
"/auth/#{provider}"
end
helper_method :signin_path
def user_path(user, *args)
options = args.extract_options!
hash = {
:controller => '/users',
:action => 'show',
:service => user.service_name,
:user => user.user_name,
}
hash.merge(options)
end
helper_method :user_path
def user_url(*args)
url_for user_path(*args)
end
def current_user=(user)
session[:user_id] = user.id
user.update_attribute(:last_signin_at, Time.now)
user
end
def current_user
if session[:user_id]
@current_user ||= UserPresenter.new(User.find(session[:user_id]))
end
end
helper_method :current_user
def can_edit?(user: @user, project: @project)
return false unless logged_in?
if project
Action::Project::Update.can_edit?(current_user, project)
elsif user
user.id == current_user.id
end
end
helper_method :can_edit?
def logged_in?
!current_user.nil?
end
helper_method :logged_in?
def require_login
unless logged_in?
render :text => 'You need to be signed in.', :status => 401
false
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/admin/builds_controller.rb | app/controllers/admin/builds_controller.rb | require 'inch_ci/controller'
class Admin::BuildsController < ApplicationController
include InchCI::Controller
layout 'admin'
PER_PAGE = 200
def index
set_builds
@languages = %w(Elixir JavaScript Ruby)
@gossip_room = "projects:lobby"
end
def show
view = Action::Build::Show.new(params, load_dump: true)
expose view
end
private
def set_builds
@builds = find_builds.map do |build|
BuildPresenter.new(build)
end
@scheduled_builds = @builds.select { |b| b.status == 'created' }
@running_builds = @builds.select { |b| b.status == 'running' }
@completed_builds = @builds.select { |b| !%w(created running).include?(b.status) }
end
def filter_collection(arel)
arel = arel.references(:branch).joins(:project)
if params[:language].present?
arel = arel.where('LOWER(projects.language) = ?', params[:language].to_s.downcase)
end
if params[:statuses].present?
@statuses = params[:statuses]
arel = arel.where(:status => @statuses)
end
if params[:triggers].present?
@triggers = params[:triggers]
arel = arel.where(:trigger => @triggers)
end
if uid = params[:uid].presence
arel = arel.where('projects.uid LIKE ?', "%#{uid}%")
end
if params[:service]
arel = filter_by_service_and_user(arel, params[:service], params[:user], params[:repo])
end
arel
end
def filter_by_service_and_user(arel, service, user_name, repo_name)
like = "#{service}:"
if user_name
like << "#{user_name}/"
end
if repo_name
like << "#{repo_name}"
end
arel.where('projects.uid LIKE ?', like+'%')
end
def find_builds
arel = filter_collection(Build).order('created_at DESC')
@builds_total_count = arel.count
arel.limit(PER_PAGE)
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/admin/projects_controller.rb | app/controllers/admin/projects_controller.rb | require 'inch_ci/controller'
class Admin::ProjectsController < ApplicationController
include InchCI::Controller
PROJECTS_PER_PAGE = 200
LANGUAGE_NOT_SET = "LANGUAGE_NOT_SET"
layout 'admin'
def create
action = Action::Project::Create.new(params, :admin)
if action.success?
redirect_to project_url(action.project, :pending_build => action.build_id)
else
expose action
flash[:error] = t("projects.create.url_not_found")
render :template => "page/welcome"
end
end
def update
@project = ::Project.find(params[:id])
attributes = params[:project]
@project.documentation_url = attributes[:documentation_url]
@project.language = attributes[:language]
InchCI::Store::SaveProject.call(@project)
redirect_to admin_project_url(@project)
end
def index
@projects = find_projects
@languages = %w(Elixir JavaScript Ruby) + [LANGUAGE_NOT_SET]
end
def find_projects
arel = filter_collection(Project).order('created_at DESC')
@projects_total_count = arel.count
arel.limit(PROJECTS_PER_PAGE)
end
def show
@project = Project.find(params[:id])
end
private
def filter_collection(arel)
if params[:language].present?
if params[:language] == LANGUAGE_NOT_SET
arel = arel.where('language IS NULL')
else
arel = arel.where('LOWER(language) = ?', params[:language].to_s.downcase)
end
end
if params[:fork].present?
arel = arel.where(:fork => params[:fork] == '1')
end
if params[:badge_in_readme].present?
arel = arel.where(:badge_in_readme => params[:badge_in_readme] == '1')
end
if params[:badge_generated].present?
arel = arel.where(:badge_generated => params[:badge_generated] == '1')
end
if filled = params[:badge_filled_greater_than].presence
arel = arel.where('badge_filled_in_percent >= ?', filled)
end
if params[:maintainers_with_badge_in_readme].present?
projects = Project.where(:badge_in_readme => true)
likes = projects.map do |project|
"#{project.service_name}:#{project.user_name}/%"
end.uniq
conditions = (['uid LIKE ?'] * likes.size).join(' OR ')
arel = arel.where(conditions, *likes)
end
if uid = params[:uid].presence
arel = arel.where('uid LIKE ?', "%#{uid}%")
end
if params[:service]
arel = filter_by_service_and_user(arel, params[:service], params[:user])
end
arel
end
def filter_by_service_and_user(arel, service, user_name)
like = "#{service}:"
if user_name
like << "#{user_name}/"
end
arel.where('uid LIKE ?', like+'%')
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/admin/statistics_controller.rb | app/controllers/admin/statistics_controller.rb | class Admin::StatisticsController < ApplicationController
layout 'admin'
def index
weeks
end
DAYS_BACK = 21
def days
set_stats do
Statistics.where("date > ?", time_units_back_timestamp(:days, DAYS_BACK))
end
render :action => "index"
end
WEEKS_BACK = 20
def weeks
set_stats do
Statistics.where("WEEKDAY(date) = 0 AND date > ?", time_units_back_timestamp(:weeks, WEEKS_BACK))
end
render :action => "index"
end
MONTHS_BACK = 24
def months
set_stats do
Statistics.where("DAY(date) = 2 AND date > ?",time_units_back_timestamp(:months, MONTHS_BACK))
end
render :action => "index"
end
private
def time_units_back_timestamp(unit, default)
time_units = time_units_back(default)
return 0 if time_units == 'all'
# we shift the first stats, so we have to load 1 additional record
(time_units.to_i + 1).send(unit).ago
end
def time_units_back(default = nil)
@time_units_back ||= params[:time_units_back] || default
end
helper_method :time_units_back
def set_stats(&block)
list = block.call.order('date ASC')
map = map_stats_to_dates(list)
@stats = Stats.new(map)
end
# Maps the given list of Statistic objects to their date's day.
def map_stats_to_dates(list)
map = {}
list.each do |stat|
date = stat.date.midnight
map[date] ||= {'date' => date.strftime("%Y-%m-%d")}
map[date][stat.name] = stat.value
end
map
end
def stat(name)
Statistics.where(:name => name).last.value
end
def quotient(name1, name2, digits = 2)
(stat(name1).to_f / stat(name2).to_f).round(digits)
end
def val(stats, key, add_change = true)
@old_stats ||= {}
value = stats[key].to_i
change = value - @old_stats[key].to_i
change = "+#{change}" if change > 0
result = value.to_s
if key == "projects:badges"
url = url_for(:controller => 'admin/badges', :action => 'added',
:date_to => stats['date'], :date_from => @old_stats['date'])
result << " (<a href=\"#{url}\">#{change}</a>)"
end
if add_change
result << " (#{change})"
end
@old_stats['date'] = stats['date']
@old_stats[key] = value
result.html_safe
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/admin/users_controller.rb | app/controllers/admin/users_controller.rb | require 'inch_ci/controller'
class Admin::UsersController < ApplicationController
include InchCI::Controller
layout 'admin'
def index
@users = sort_collection(User)
@languages = InchCI::Config::LANGUAGES
end
private
def sort_collection(arel)
arel.order('created_at DESC')
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/admin/overview_controller.rb | app/controllers/admin/overview_controller.rb | class Admin::OverviewController < ApplicationController
layout 'admin'
def index
set_stats
respond_to do |format|
format.html do
set_chart_data
set_newsfeed
set_projects
end
format.json do
@pending_builds_24 = Build.where("created_at > ?", 24.hours.ago).where(:status => "created").count
@pending_builds_48 = Build.where("created_at > ?", 48.hours.ago).where(:status => "created").count
@success_builds_24 = Build.where("created_at > ?", 24.hours.ago).where(:status => "success").count
end
end
end
private
DAYS_BACK = 30
def set_stats
list = Statistics.where("date > ?", (DAYS_BACK + 1).days.ago).order('date ASC')
map = map_stats_to_dates(list)
@stats_headers = %w(Day Date Badges Users Hooks Users Repos Users)
@stats = map.keys.sort.map do |date|
stats = map[date]
shown_date = date - 1
[
shown_date.strftime("%a"),
shown_date.strftime("%Y-%m-%d"),
val(stats, 'projects:badges'),
val(stats, 'maintainers:badges'),
val(stats, 'projects:hooked'),
val(stats, 'maintainers:hooked'),
val(stats, 'projects:all'),
val(stats, 'maintainers:all'),
]
end
@stats_badges = stat('projects:badges')
@stats_badges_elixir = stat('projects:badges:elixir')
@stats_badges_javascript = stat('projects:badges:javascript')
@stats_badges_ruby = @stats_badges - @stats_badges_elixir - @stats_badges_javascript
@stats_badge_users = stat('maintainers:badges')
@stats_badges_per_user = quotient('projects:badges', 'maintainers:badges')
@stats_hooks_per_user = quotient('projects:hooked', 'maintainers:hooked')
@stats_chart_data = map.values
end
def set_chart_data
list = Statistics.order('date ASC').group('name, WEEK(date)')
map = map_stats_to_dates(list)
@absolutes_by_week = map.values
@growth_by_week = []
@absolutes_by_week.each_with_index do |value, index|
if index > 0
last_value = @absolutes_by_week[index-1]
new_value = {'date' => value['date']}
value.each do |key, v|
if v.is_a?(Fixnum)
new_value[key] = v - last_value[key].to_i
end
end
@growth_by_week << new_value
end
end
end
# Maps the given list of Statistic objects to their date's day.
def map_stats_to_dates(list)
map = {}
list.each do |stat|
date = stat.date.midnight
map[date] ||= {'date' => date.strftime("%Y-%m-%d")}
map[date][stat.name] = stat.value
end
map
end
def set_newsfeed
base_date = Time.now #Time.parse('2015-04-26')
@newsfeed = (1..14).to_a.reverse.map do |index|
date = base_date - index.days
NewsfeedDay.new(date)
end
end
def set_projects
@new_projects = Project.includes(:default_branch)
.where(:badge_generated => true)
.order('created_at ASC')
.last(30)
end
def stat(name)
statistic = Statistics.where(:name => name).last
(statistic && statistic.value).to_i
end
def quotient(name1, name2, digits = 2)
(stat(name1).to_f / stat(name2).to_f).round(digits)
end
def val(stats, key, add_change = true)
@old_stats ||= {}
value = stats[key]
change = value - @old_stats[key].to_i
change = "+#{change}" if change > 0
@old_stats[key] = value
result = value.to_s
result << " (#{change})" if add_change
result
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/admin/cli_controller.rb | app/controllers/admin/cli_controller.rb | require 'inch_ci/controller'
class Admin::CliController < ApplicationController
include InchCI::Controller
layout 'admin'
def index
expose Action::CLI::ListDumps.new(params)
expose Action::CLI::GetDump.new(params)
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/admin/badges_controller.rb | app/controllers/admin/badges_controller.rb | class Admin::BadgesController < ApplicationController
layout 'admin'
def added
@date_from = Date.parse(params[:date_from])
@date_to = Date.parse(params[:date_to])
@projects_from = projects_with_badges_before(@date_from)
@projects_to = projects_with_badges_before(@date_to)
@projects = @projects_to - @projects_from
end
def in_readme
@projects = projects_with_badges_before(Time.now)
end
private
def projects_with_badges_before(timestamp)
Project.all.where(:badge_in_readme => true)
.where('created_at <= ?', timestamp)
.where('badge_in_readme_added_at <= ?', timestamp)
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/api/builds_controller.rb | app/controllers/api/builds_controller.rb | require 'inch'
require 'fileutils'
require 'inch_ci/worker/project/build_json'
module Api
class BuildsController < ApplicationController
protect_from_forgery with: :null_session
def hint
render_text "> Greetings, Professor Falken.\n\n> _\n"
end
def run
# let's ensure backwards compatibility
params[:language] = 'javascript' if params[:language] == 'nodejs'
if valid_params?
file = dump_request_to_file
if build = enqueue_build(file.path)
copy_file(file, build)
update_project_if_necessary(build.project)
render_text "Successfully created build ##{build.number}\n" \
"URL: #{project_url(build.project)}\n"
else
render_text "[ERROR] Build could not be created.\n"
end
else
render_text "[ERROR] #{@param_errors}\n"
end
end
private
def dump_request_to_file
write_file filename_with_extension, JSON.pretty_generate(params)
end
def enqueue_build(filename)
InchCI::Worker::Project::BuildJSON.enqueue(filename)
end
def filename_for_build(build)
Rails.root.join('dumps', 'builds', "build-#{build.id}.json")
end
def filename_with_extension
dir = Rails.root.join('dumps', 'builds', language_from_params, Time.now.strftime('%Y%m%d'))
File.join(dir, request.object_id.to_s + '.json')
end
def language_from_params
params[:language]
end
def copy_file(file, build)
FileUtils.copy file.path, filename_for_build(build)
end
def render_text(text)
render :text => text, :content_type => "text/plain"
end
def update_project_if_necessary(project)
if !project.default_branch # this project is new
worker = InchCI::Worker::Project::UpdateInfo.new
worker.perform(project.uid)
end
end
def write_file(filename, contents)
FileUtils.mkdir_p File.dirname(filename)
file = File.new(filename, 'w')
file.write contents
file.close
file
end
def valid_params?
if language_from_params.to_s.empty?
@param_errors = "No language defined."
end
@param_errors.nil?
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/controllers/api/cli_controller.rb | app/controllers/api/cli_controller.rb | require 'inch'
require 'inch/cli'
require 'inch/utils/ui'
require 'inch/utils/buffered_ui'
require 'fileutils'
module Api
class CliController < ApplicationController
protect_from_forgery with: :null_session
def hint
render_text "> Greetings, Professor Falken.\n\n> _\n"
end
def run
# let's ensure backwards compatibility
params[:language] = 'javascript' if params[:language] == 'nodejs'
if valid_params?
dump = dump_request_to_file
args = cli_args(dump) + [{:ui => buffered_ui}]
command = ::Inch::CLI::CommandParser.run(*args)
dump_output_to_file
render_text buffered_ui.buffer
else
render_text "[ERROR] #{@param_errors}\n"
end
rescue SystemExit => e
render_text buffered_ui.buffer
end
private
def buffered_ui
@buffered_io ||= ::Inch::Utils::BufferedUI.new
end
def cli_args(dump)
args_from_params + ["--language=#{language_from_params}", "--read-from-dump=#{dump.path}"]
end
def dump_request_to_file
write_file filename_with_extension(:json), JSON.pretty_generate(params)
end
def dump_output_to_file
write_file filename_with_extension(:out), buffered_ui.buffer
end
def filename_with_extension(ext)
dir = Rails.root.join('dumps', 'cli', language_from_params, Time.now.strftime('%Y%m%d'))
File.join(dir, request.object_id.to_s + '.' + ext.to_s)
end
def args_from_params
params[:args] || []
end
def command_from_args
args_from_params.first
end
def language_from_params
params[:language]
end
def render_text(text)
render :text => text, :content_type => "text/plain"
end
def write_file(filename, contents)
FileUtils.mkdir_p File.dirname(filename)
file = File.new(filename, 'w')
file.write contents
file.close
file
end
VERBOTEN_COMMANDS = %w(diff inspect console)
def valid_params?
if language_from_params.to_s.empty?
@param_errors = "No language defined."
end
if VERBOTEN_COMMANDS.include?(command_from_args)
@param_errors = "The '#{command_from_args}' command is not supported via API.\n\nIf you want to use it, you have to install Inch locally."
end
@param_errors.nil?
end
end
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
inch-ci/inch_ci-web | https://github.com/inch-ci/inch_ci-web/blob/db1437218f544e4f21bdfd3690a952bf26a84028/app/models/project.rb | app/models/project.rb | require 'inch_ci/project_uid'
class Project < ActiveRecord::Base
UID_FORMAT = /\A([a-z0-9\-\_\.]+)\:([a-z0-9\-\_\.]+)\/([a-z0-9\-\_\.]+)\Z/i
has_many :branches, :dependent => :destroy
has_many :code_objects, :dependent => :destroy
belongs_to :default_branch, :class_name => 'Branch'
has_many :builds, :through => :branches
serialize :languages
def self.find_by_uid(uid)
uid = "github:#{uid}" if uid !~ /\:/
where(:uid => uid).first
end
def user
User.where(:provider => service_name, :user_name => user_name).first
end
# TODO: implement another way
def service_name
@service_name ||= InchCI::ProjectUID.new(uid).service
end
# TODO: implement another way
def user_name
@user_name ||= InchCI::ProjectUID.new(uid).user_name
end
# TODO: implement another way
def repo_name
@repo_name ||= InchCI::ProjectUID.new(uid).repo_name
end
validates :uid, :format => UID_FORMAT, :presence => true, :uniqueness => true
validates :repo_url, :presence => true, :uniqueness => true
end
| ruby | MIT | db1437218f544e4f21bdfd3690a952bf26a84028 | 2026-01-04T17:44:13.103953Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.