text stringlengths 10 2.61M |
|---|
module Disqussion
class Reports < Client
# Returns report on domains
# @accessibility: public key, secret key
# @methods: GET
# @format: json, jsonp
# @authenticated: false
# @limited: false
# @param options [Hash] A customizable set of options.
# @option options [Integer] :limit. Defa... |
class AddCardsTable < ActiveRecord::Migration
def change
create_table :cards do |t|
t.string :number
t.integer :cvv
t.string :expiry
t.string :fullname
t.references :user, index: true
end
end
end
|
class AddImageToAnimes < ActiveRecord::Migration[5.2]
def change
add_column :animes, :banner, :string
add_column :animes, :cover_large, :string
add_column :animes, :cover_medium, :string
end
end
|
require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper'))
class ForeignKeyConstraintsTest < Test::Unit::TestCase
def schema_dump
stream = StringIO.new
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
stream.rewind
stream.read
end
def schema(&block)
Ac... |
require 'faker'
FactoryGirl.define do
factory :production_plan do
dt_scheduled { Faker::Date.between(Date.today, 7.days.from_now) }
product_id { FactoryGirl.create(:final_product).id }
customer_id { FactoryGirl.create(:customer).id }
qty_scheduled { Faker::Number.between(1, 100) }
qty_produced 0
... |
class CreateReturns < ActiveRecord::Migration
def change
create_table :returns do |table|
# Create as a copy of 'charges' table
Charge.columns.each do |column|
next if column.name == "id" # already created by create_table
table.send(column.type.to_sym, column.name.to_sym, :null => col... |
module Webex
module User
# comment
class Partner
include Webex
include Webex::User
attr_accessor :webex_id, :ticket, :password, :back_type, :back_url, :email,
:session, :first_name, :last_name, :new_password
def initialize(attributes = {})
attributes.each { ... |
class PlayerStat < ActiveRecord::Base
belongs_to :player
belongs_to :game
end
|
require 'compiler'
class NotesController < ApplicationController
before_filter :set_compiler
helper_method :get_name
def set_compiler
@compiler = Compiler.new
end
def new
@note = Note.new
end
def index
@notes = Note.all
end
def create
@book = Book.find(params[:book_id])
@note ... |
class CreateOrders < ActiveRecord::Migration
def change
Cms::ContentType.create!(:name => "Order", :group_name => "Order")
create_content_table :orders, :prefix=>false do |t|
t.string :phone_no
t.text :address
t.integer :total
t.datetime :date
t.string :status
t.timestamps... |
class Book < ActiveRecord::Base
belongs_to :author
has_many :chapters, dependent: :destroy
has_one :foreword, dependent: :destroy
end
|
class Admin::RegistrationsController < Devise::RegistrationsController
before_action :check_permissions, :only => [:new, :create, :destroy]
skip_before_action :require_no_authentication
protected
def check_permissions
authorize! :create, resource
end
end
|
# frozen_string_literal: true
module J8
class Consumer
include J8::Common
def accept(o)
@callable.call(o)
end
def then(after = nil, &block)
callable = from_callable(after, block)
J8::Consumer.new(
lambda do |o|
accept(o)
callable.accept(o)
end
... |
# frozen_string_literal: true
require 'spec_helper'
describe Monologue::Admin::PostsController, type: :controller do
let(:user) { create(:user) }
before do
sign_in_as user
@routes = Monologue::Engine.routes
end
describe 'PUT #update' do
let(:post) { create(:post) }
let(:new_content) { 'This is... |
class OrdersController < ApplicationController
# POST /orders
# create an order
def create
@order = Order.new
@email = params[:email]
@id = params[:itemId]
#get a customer by passing in their email
#returns an error if it's not found
@code, @cust... |
#!/usr/bin/env ruby
#
# * Nagios plugin to check AWS autoscaling group status
#
require 'rubygems'
require 'optparse'
require 'pp'
require 'aws-sdk'
require 'date'
options = {}
op = OptionParser.new do |opts|
opts.banner = "Usage: "
opts.on("-G", "--asgroup ASGNAME", "AWS AutoScaling Group name to check status for... |
require File.expand_path('../../spec_helper', __FILE__)
describe Backstage, no_database_cleaner: true do
before(:all) { module Backstage::CoolStorefront end }
describe '#storefronts' do
before(:each) { Backstage.class_variable_set(:@@storefronts, [Backstage::CoolStorefront]) }
specify { expect(Backstage.... |
class CreateContributions < ActiveRecord::Migration[6.0]
def change
create_table :contributions do |t|
t.string :type
t.string :date
t.string :contributor
t.integer :zip
t.string :employer
t.string :occupation
t.decimal :amount
t.string :committee_name
t.integ... |
class ChangePlayersToHaveDefaultRating < ActiveRecord::Migration[4.2]
def change
change_column :players, :rating, :integer, default: 0, null: false
end
end
|
require 'rails_helper'
RSpec.describe "screenings/edit", type: :view do
before(:each) do
@screening = assign(:screening, Screening.create!(
:movie => nil,
:user => nil,
:theatre => nil,
:offer => nil,
:approval_filmmaker => false,
:approval_theatre => false,
:threshold =... |
class GameserverinfosController < ApplicationController
before_action :set_gameserverinfo, only: [:show, :update, :destroy]
# GET /gameserverinfos
def index
@gameserverinfos = Gameserverinfo.all
render json: @gameserverinfos
end
# GET /gameserverinfos/1
def show
render json: @gameserverinfo
... |
=begin
#Rakam API Documentation
#An analytics platform API that lets you create your own analytics services.
OpenAPI spec version: 0.5
Contact: contact@rakam.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file e... |
class PetitionsController < ApplicationController
before_action :authorize, only: [:new, :create]
def index
@petitions = Petition.all
if params[:my]
@petitions = @petitions.where(user: current_user)
render 'my_index'
end
end
def show
@petition = Petition.find(params[:id])
end
... |
require 'spec_helper'
describe Kata::Algorithms::Sorting::QuickSelect do
[
[[0, 50, 20, 10, 60, 30], 1, 0],
[[0, 50, 20, 10, 60, 30], 2, 10],
[[0, 50, 20, 10, 60, 30], 3, 20],
[[0, 50, 20, 10, 60, 30], 4, 30],
[[0, 50, 20, 10, 60, 30], 5, 50],
[[0, 50, 20, 10, 60, 30], 6, 60],
... |
class LocalDocIdIsGone < ActiveRecord::Migration
def self.up
rename_column :list_items, :local_doc_id, :doc_id
end
def self.down
rename_column :list_items, :doc_id, :local_doc_id
end
end
|
require 'spec_helper'
describe AvatarUploader do
include CarrierWave::Test::Matchers
before do
@user = User.new
@uploader = AvatarUploader.new @user, :avatar
@uploader.store!(File.open(Rails.root.join('spec/fixtures/avatar.jpg')))
end
it "should be scaled to 50x50 pixels" do
@uploader.shoul... |
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
describe "/businesses/new.html.erb" do
include BusinessesHelper
before(:each) do
assigns[:business] = stub_model(Business,
:new_record? => true,
:name => "value for name"
)
end
it "renders new business form" do
re... |
<<<<<<< HEAD
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(secure_params)
if @user.valid?
flash[:notice] = "Szczęśliwa rejestracja!"
@user.save
redirect_to root_path
else
flash[:alert] = "Problem z hasłem!"
render "new"
end
end
def update... |
module WelcomeHelper
def greeting_for(name)
"Hello #{name}!"
end
end
|
class PigLatinizer
def piglatinize(word)
alphabet = ("A".."z").to_a
vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
consonants = alphabet - vowels
unusable = ["i", "a", "an", "in", "on", "and"]
word.gsub!(/[^a-z0-9\s]/i, '')
word = word.split(""... |
require 'spec_helper'
describe User do
it { should have_secure_password }
it { should validate_presence_of :username }
it { should have_many :questions }
end
|
def longest_password(s)
s.downcase.split(" ").uniq.sort_by(&:length).reverse.each do |pass|
return pass.length if password_correct?(pass)
end
-1
end
def password_correct?(password)
all_password_conditions_satisfied(password) ? true : false
end
def password_integers_length(password)
password.delete("^0-9... |
# frozen_string_literal: true
require "spec_helper"
RSpec.describe Helpers do
describe ".underscore" do
subject { described_class.underscore string }
context "when string is empty" do
let(:string) { "" }
it { is_expected.to eq "" }
end
context "when string is in snakecase" do
le... |
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@posts = Post.order('travel_date DESC').find(@user.posts.ids)
end
end
|
require 'rails_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold... |
require 'mechanize'
class Vent_Status
# Public Methods
def self.players(hostname, port)
agent = Mechanize.new
url = "http://www.ventrilo.com/status.php?hostname=" + hostname + "&port=" + port + ""
vent_page = agent.get(url)
get_player_info(vent_page)
end
def self.server(hostname, port)
agent = Mechan... |
require File.dirname(__FILE__) + '/../test_helper'
class TeamTest < Test::Unit::TestCase
fixtures :teams
GOOD_TEAM = {:name => "nsu3", :email => "nsu3@gorodok.net", :password => "piapugha",
:coach_names => "NSU Training", :coach_email => "tanch@iis.nsk.su"}
BAD_TEAM = {:name => "", :email => ... |
class Donor < ActiveRecord::Base
has_many :donations
has_many :users, :as => :role
has_and_belongs_to_many :campaigns
def first_donation_date(endowment_id)
self.donations.where("endowment_id = ?", endowment_id).order("created_at ASC").first.created_at.to_date rescue Date.today
end
def charity_balance... |
module Cucumber
module Formatters
class DocFormatter
def initialize(io, step_mother)
@io = io
@step_mother = step_mother
@errors = []
@scenario_table_header = []
end
def visit_features(features)
@io.puts(<<-HTML)
<?xml version="1.0" encoding="UTF-8"?>
<!D... |
control "M-1.1" do
title "Ensure a separate partition for containers has been created (Scored)"
desc "
Description:
All Docker containers and their data and metadata is
stored under /var/lib/docker directory. By default, /var/lib/docker would be
mounted under / or /var partitions based on... |
class Music < ApplicationRecord
belongs_to :genre, class_name: 'Genre', foreign_key: 'genre_id'
has_many :notecharts, class_name: 'Notechart', dependent: :destroy
end
|
# frozen_string_literal: true
require 'generators/graphql/type_generator'
module Graphql
module Generators
# Generate an enum type by name, with the given values.
# To add a `value:` option, add another value after a `:`.
#
# ```
# rails g graphql:enum ProgrammingLanguage RUBY PYTHON PERL PERL6:"... |
class Api::PortfoliosController < ApplicationController
before_action :set_portfolio, only: [:show, :update, :destroy]
def index
render json: current_user.portfolios
end
def show
render json: @portfolio
end
def create
portfolio = Portfolio.new(portfolio_params)
if portfolio.save
... |
class RemoveReferencesFromUsers < ActiveRecord::Migration[6.0]
def change
remove_reference(:users, :chef, foreign_key: true)
end
end
|
class EARMMS::BranchAdminMembersController < EARMMS::ApplicationController
get '/:branchid' do |branchid|
branchid = branchid.to_i
next halt 404 unless logged_in?
next halt 404 unless has_role? "branch:#{branchid}:list"
@branch = EARMMS::Branch[branchid]
next halt 404 unless @branch
@branchna... |
# All Administrate controllers inherit from this `Admin::ApplicationController`,
# making it the ideal place to put authentication logic or other
# before_actions.
#
# If you want to add pagination or other controller-level concerns,
# you're free to overwrite the RESTful controller actions.
module Admin
class Applic... |
class AddRatingToSolrPhotos < ActiveRecord::Migration
def change
add_column :solr_photos, :rating, 'int unsigned', :default => 0, :null => false, :after => :cluster_name
end
end
|
class Livestock < ActiveRecord::Base
belongs_to :animal
belongs_to :farmer
has_many :products
end
|
class Event < ApplicationRecord
has_many :tickets
has_many :ticket_bookings,through: :tickets
has_many :users,through: :tickets
end
|
class AddStatusToPlaces < ActiveRecord::Migration[5.0]
def change
add_column :places, :status, :string
end
end
|
#Author: John Kilfeather
require 'Terrain.rb'
require 'MatrixStats.rb'
require 'Square.rb'
class Helicopter
include MatrixStats
def initialize terrain
@terrain = terrain
end
def find_location
biggest_square = Square.new 0, 0, 0, 0;
#2d array storing the biggest square possible at each location
count = ... |
module Sword
module Metadata
class ParentPublication
attr_accessor :doi,
:issue,
:publish_date,
:start_page,
:title,
:uri,
:volume
end
end
end
|
class FulfillmentController < ApplicationController
before_action :authenticate_user!
helper_method :sort_column, :sort_direction, :classed_remove
def index
@orders = Order.fulfill_orders
end
private
def sort_column
%w[c_ship c_date c_total c_name].include?(params[:sort]) ? params[:sort] : "c_date"... |
require "bundler/gem_tasks"
require 'rake/testtask'
namespace :test do
adapters = [ :postgresql ]
task :all => [ :procedural ] + adapters
adapters.each do |adapter|
Rake::TestTask.new(adapter) do |t|
t.libs.push "lib"
t.libs.push "spec"
t.pattern = "spec/adapters/#{t.name}*_spec.rb"
... |
module SocratesScrapper
class Scrapper
def initialize agent, url
@agent = agent
@page = load_socrates_page(url)
end
def load_socrates_page url
@agent.get(url)
end
def submit_form
form = @page.form
form.email = ENV['SOCRATES_EMAIL']
form.password = ENV['SOCRAT... |
#!/usr/bin/env ruby
class PascalsTriangle
def factorial(n)
raise "cannot make a factorial of #{n}" if n < 0
(1..n.to_i).reduce(1, :*)
end
# optimizes n! / r! = n * (n-1) * (n-2) * ... * (r-1)
def factorial_without(n, r)
raise "#{r} is greater than #{n}" if r > n
return n if r == n
((r+1).... |
require 'rails_helper'
RSpec.describe Card, type: :model do
it { should have_valid(:name).when('Arcane Angel', 'The Rack') }
it { should_not have_valid(:name).when(nil, '') }
it { should have_valid(:artist).when('Arcane Angel', 'The Rack') }
it { should_not have_valid(:artist).when(nil, '') }
it { should ... |
module HQMF2JS
module Generator
class Execution
def self.quoted_string_array_or_null(arr)
if arr
quoted = arr.map {|e| "\"#{e}\""}
"[#{quoted.join(',')}]"
else
"null"
end
end
# Note that the JS returned by this function is not included whe... |
require "rubii/keymap/linux_xdotool"
module Rubii
module Linux
module XDoTool
Config = {
:wiimote => {
:buttons => {
:digital => {
:home => {
:rise => NullEvent,
:fall => NullEvent
},
:up => {... |
api_version(module: "V1", header: {name: "Accept", value: "application/bebras.tw; ver=1"}) do
scope module: :dashboards, format: false do
namespace :admin do
resource :users, only: [] do
get "/" => "users#index"
end
resources :user, only: [] do
collection do
get "list/:... |
class Image < ActiveRecord::Base
belongs_to :project
has_attached_file :attachment,
styles: {thumb: "100x70#", medium: "300x210#", large: "600x400#", largest: "1200x800#"},
storage: :s3,
bucket: 'micromakers',
s3_credentials: {
... |
class CreateProductPublishers < ActiveRecord::Migration[5.0]
def change
create_table :product_publishers do |t|
t.references :product, foreign_key: true, index: true
t.references :publisher, foreign_key: true, index: true
t.timestamp
end
end
end
|
Gem::Specification.new do |gem|
gem.authors = ['Taras Kunch']
gem.email = ['tkunch@rebbix.com']
description = 'Logger for Rails that sends data to fluentd'
gem.description = description
gem.summary = description
gem.files = `git ls-files`.split($\)
gem.executables =... |
#spec/factories/authors.rb
require 'faker'
FactoryGirl.define do
factory :author do
website { Faker::Internet.domain_name }
name "#{ Faker::Name.first_name } #{ Faker::Name.last_name }"
factory :author_with_books do
after(:build) do |author|
3.times do
author.books << FactoryGirl.... |
require 'rubygems'
require 'color'
require 'chunky_png'
require 'narray'
module HeatPalette
HSL_HUE_MIN = 0
HSL_HUE_MAX = 180
HSL_SATURATION = 90
HSL_LIGHTNESS = 50
Rainbow = (HSL_HUE_MIN...HSL_HUE_MAX).map do |hue|
Color::HSL.new(hue, HSL_SATURATION, HSL_LIGHTNESS).to_rgb.hex
end
end
class HeatMap
... |
require 'test/unit'
require_relative '../jmeter_reporter'
require 'hash_diff'
require 'json'
$base_dir = File.expand_path(File.dirname(__FILE__))
class TC_MyTest < Test::Unit::TestCase
# basic test with some diverse sample data to ensure that
# things like percentile calculations and handling errors
# are st... |
#!/usr/bin/env ruby
require File.join(File.dirname(__FILE__), "..", "spec_helper")
describe "Macro:" do
before do
create_web_project
Glyph['document.output'] = 'web'
Glyph.run! 'load:all'
end
after do
Glyph.lite_mode = false
reset_quiet
delete_project
end
it "section (topic)" do
expect { output_f... |
class Article < ApplicationRecord
# Relation
belongs_to :user
has_many :comments
# настраиваем валидацию полей (свойств) модели
validates :title, :text, presence: true
end
|
class Turn < ApplicationRecord
validates :player_id, :game_id, presence: true
validates :completed, inclusion: { in: [true, false] }
belongs_to :player
belongs_to :game
belongs_to :roll, optional: true
belongs_to :start_space, class_name: 'Space', primary_key: :id, foreign_key: :start_space_id, optional: t... |
#
# Cookbook :: ambari
# Recipe :: postgres_server_embedded_setup
# Copyright 2018, Bloomberg Finance L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/... |
class Api::V1::StoresController < Api::ApiV1Controller
def create
@store = Store.new store_params
if @store.save
render :store
else
response_error(title: 'Could not register', code: 31, reasons: @store.errors.messages, description: "There are invalid values", status_code: 422)
end
end
... |
require_relative '02_searchable'
require 'active_support/inflector'
# Phase IIIa
class AssocOptions
attr_accessor(
:foreign_key,
:class_name,
:primary_key
)
def model_class
class_name.constantize
end
def table_name
name = class_name.to_s.underscore.pluralize
name == "humen" ? "human... |
class Play < ActiveRecord::Base
MAX_PLAYER_COUNT = 2
has_many :user, :as => :turn_player
has_many :user, :as => :first_player
has_many :user, :as => :last_player
has_many :user, :as => :winner
validates :room_no, presence: true
validates :state, presence: true
def end?
self.state == "finish" || sel... |
require 'spec_helper'
RSpec.describe 'array' do
subject(:a1) { [1,2,3].timed("2014") }
it 'init hour array' do
expect(a1).to be_an_instance_of(TimeArray::TimeArray)
end
end |
# frozen_string_literal: true
ActiveAdmin.register User do
permit_params :email, :role, :name, :github_handle, :twitter_handle, :password, :password_confirmation
actions :all, except: [:destroy]
menu priority: 1000
index do
selectable_column
id_column
column :name
column :role
column :emai... |
# encoding: utf-8
require 'mail_helper'
module MicropostHelper
include MailHelper
def send_email_if_registered_usernames(sender, message)
user_names = extract_user_names(message)
if !user_names.empty?
emails = get_emails(user_names)
if !emails.empty?
send_simple_message(sender, emails,... |
class SuggestedProduct < ApplicationRecord
belongs_to :user
mount_uploader :image, ProductUploader
validates :name,
presence: true,
length: {maximum: Settings.validation.name}
validates :price,
presence: true,
numericality: {greater_than_or_equal_to: Sett... |
require 'spec_helper'
feature 'User adds a topic', %q{
As a user,
I would like to add a topic,
so that it can be discussed during a workshop.} do
# Acceptance Criteria
# I go to the “Add a Topic” page and enter the following information into a form
# The topic headline
# The topic description
# The topic category
# I ... |
#!/usr/bin/env ruby
require_relative '../cellect_env'
require 'pg'
require 'csv'
require "fileutils"
class BootstrapPanoptes
include CellectEnv
DATA_DIR = 'tmp'
SUBJECT_DIST = 500000
FILE_PREFIX = "#{DATA_DIR}/#{SUBJECT_DIST}"
USER_COUNT = 10_000
RETIREMENT_COUNT = 15
PROJECT_ID = 1
WORKFLOW_ID = 1
... |
module Jekyll
class Renderer
def render_layout(output, layout, info)
ProjectHyde::CssProcessor.new(layout, info).process
# Would be nice to call super here instead of cloned logic
payload["content"] = output
payload["layout"] = Utils.deep_merge_hashes(layout.data, payload["layout"] || {}... |
# encoding: utf-8
class Competence < ActiveRecord::Base
has_many :formation_of_competences
attr_accessible :comp_group, :comp_name, :comp_subgroup
validates_presence_of :comp_group, :on => :create, :message => "Впишите шифр компетенции"
validates_presence_of :comp_name, :on => :create, :message => "Заполните с... |
module Kiik
class Client
attr_reader :site
attr_accessor :token, :options
def initialize(token, options={}, &block)
opts = options.dup
@token = token
@site = opts.delete(:site)
ssl = opts.delete(:ssl)
@options = {:connection_opts => {},
:connection_build... |
class SaveRowShelvesTrays
prepend SimpleCommand
# NOTE:
# - This method is called when user proceed to configure row details
# - Generate the shelves & trays based on row record data
# @form_object = UpdateRowInfoForm
def initialize(form_object)
@form_object = form_object
end
def call
save_rec... |
require 'cfpropertylist'
module Safari
class SafariProvider
def debug_print_root(data)
puts "Examining root node"
puts " Fields:"
data.keys.each do |key|
puts " #{key}"
end
puts " Root children:"
root_children = data["Children"]
root_children.each do |root... |
class NavigationPage
include PageObject
link(:products_and_platform, :href => '/platform-products/deliver-features-users-love-faster')
link(:events, :href => '/events')
def compare_editions
products_and_platform
#https://github.com/cheezy/page-object/wiki/Ajax-Calls
#The line below substitute this:
# w... |
require 'pry'
WIN_COMBINATIONS = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def display_board (board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "--------... |
require 'test_helper'
class VideosControllerTest < ActionController::TestCase
setup do
@video = videos(:one)
@trail = trails(:one)
@admin = users(:admin)
end
test "should get new" do
sign_in(@admin)
get :new
assert_response :success
end
test "should create video" do
sign_in(@adm... |
class ReviewsController < ApplicationController
before_filter :signed_in_user, only: [:create, :destroy]
def index
@review = Review.all
end
def create
@review = current_user.reviews.build(params[:review])
if @review.save
flash[:success] = "Review created!"
redirect_to movie_path(@rev... |
Gem::Specification.new do |s|
s.name = "opengl-cube"
s.version = "0.0.1"
s.default_executable = "opengl-cube"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Gao Chao"]
s.date = %q{2012-10-21}
s.description = %... |
# Write a program that will take a string of digits and give you all the possible consecutive number series of length n in that
# string.
#
# For example, the string "01234" has the following 3-digit series:
# => 012
# => 123
# => 234
#
# And the following 4-digit series:
# => 0123
# => 1234
class Series
a... |
class Article < ActiveRecord::Base
# validates :title, presence: true, length: { minimum: 5 }
has_many :comments, dependent: :destroy
# method: 1
validates :title, :text, presence: true, length: { minimum: 5 }
before_validation :ensure_login_has_a_value
protected
def ensure_login_has_a_value
if... |
Rails.application.routes.draw do
post 'user_token' => 'user_token#create'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
# Home controller routes.
# root 'home#index'
get 'auth' => 'home#auth'
# Get login token from Knock
post ... |
class ProjectsController < ApplicationController
def index
@projects = Project.all
if session[:title] and Project.exists?(session[:title])
@project = Project.find(session[:title])
elsif Project.first.nil?
@project = Project.new
else
@project = Project.first
session[:title] = @project[... |
require 'harness'
run_benchmark(50) do
# 500K calls
500000.times do |i|
# Call 10 times to reduce loop overhead, emphasize call performance
itself
itself
itself
itself
itself
itself
itself
itself
itself
itself
end
end
|
class Bid < ApplicationRecord
belongs_to :item
belongs_to :user, optional: true
after_create :notify_user_about_higher_bid
def notify_user_about_higher_bid
highest_bid_value = item.bids.order("value DESC").first
unless highest_bid_value.user != user
ApplicationMailer.higher_bid_failed(user, item... |
require_relative '../spec_helper'
describe Article do
it "should require a body" do
article = build(:article, :body => '')
article.should have_error_on(:body).with_message("can't be blank")
end
it "should format body with markdown" do
article = create(:article, :body => 'some _text_ using **markdow... |
class StatDecorator < Draper::Decorator
delegate_all
# Define presentation-specific methods here. Helpers are accessed through
# `helpers` (aka `h`). You can override attributes, for example:
# TODO create specs for these
def cost_per_lead
if object.cost_per_lead.is_a? Float
h.number_to_currency(ob... |
require 'net/http'
require 'nokogiri'
require 'uri'
module Feed2Email
class OPMLExporter
MAX_REDIRECTS = 10
def self.export(path)
require 'feed2email/feed'
open(path, 'w') do |f|
uris = Feed.by_smallest_id.select_map(:uri)
if new(uris).export(f) > 0
uris.size
... |
class Travelport::Model::AirSegment < Travelport::Model::Base
include Extensions::Collection
attr_accessor :flight_details,
:key,
:group,
:carrier,
:flight_number,
:origin,
:destination,
:departure_time,... |
class PostsController < ApplicationController
before_action :authenticate_user!, :except => [:index, :show]
# index of posts for current user
def index
if current_user
@all_posts = current_user.posts
else
@all_posts = Post.all
end
end
# retrieve a single post and render the show page
def show
@po... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.