Top Banner
9. CÓDIGO FUENTE Modelos ACCOUNT class Account < ActiveRecord::Base file_column :avatar, :magick=> {:crop=>"1:1",:geometry=>"75x75"} validates_presence_of :login, :password, :message=> "Debes rellenar los dos campos" validates_uniqueness_of :login, :message=>"Ese login ya esta en uso, por favor, elija otro" validates_uniqueness_of :emailagencia, :message=>"Ese e-mail ya está en uso, por favor, elija otra" def password=(str) write_attribute("password", Digest::SHA1.hexdigest(str)) end def password "********" end def self.authenticate(l, p) find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas end ADMIN class Admin < ActiveRecord::Base require 'digest/sha1' has_one :viaje validates_presence_of :login, :password, :telefono, :message=> "Debes rellenar los dos campos" validates_uniqueness_of :login, :message=>"Ese login ya esta en uso, por favor, elige otro" def password=(str) write_attribute("password", Digest::SHA1.hexdigest(str)) end def password "********" end def self.authenticate(l, p) find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end end
87

9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Sep 07, 2018

Download

Documents

doandang
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

9. CÓDIGO FUENTE Modelos ACCOUNT class Account < ActiveRecord::Base file_column :avatar, :magick=> {:crop=>"1:1",:geometry=>"75x75"} validates_presence_of :login, :password, :message=> "Debes rellenar los dos campos" validates_uniqueness_of :login, :message=>"Ese login ya esta en uso, por favor, elija otro" validates_uniqueness_of :emailagencia, :message=>"Ese e-mail ya está en uso, por favor, elija otra"

def password=(str) write_attribute("password", Digest::SHA1.hexdigest(str)) end

def password "********" end def self.authenticate(l, p) find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas end ADMIN class Admin < ActiveRecord::Base require 'digest/sha1' has_one :viaje validates_presence_of :login, :password, :telefono, :message=> "Debes rellenar los dos campos" validates_uniqueness_of :login, :message=>"Ese login ya esta en uso, por favor, elige otro"

def password=(str) write_attribute("password", Digest::SHA1.hexdigest(str)) end def password "********" end def self.authenticate(l, p) find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end end

Page 2: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

113

DESTINO class Destino < ActiveRecord::Base belongs_to :user belongs_to :viaje validates_size_of :observaciones, :maximum => 50, :message => "maximo 50 caracteres" end

OFERTA class Oferta < ActiveRecord::Base belongs_to :viaje belongs_to :account has_many :votos validates_size_of :comentario, :maximum => 50, :message => "maximo 50 caracteres" end

USER require 'digest/sha1' class User < ActiveRecord::Base has_many :votos has_one :destino belongs_to :viaje attr_accessor :password file_column :avatar, :magick=> {:crop=>"1:1",:geometry=>"75x75"} #validates_spanish_vat :dni validates_presence_of :login, :email validates_presence_of :password, :if => :password_required? validates_presence_of :password_confirmation, :if => :password_required? validates_length_of :password, :within => 4..40, :if => :password_required? validates_confirmation_of :password, :if => :password_required? validates_length_of :login, :within => 3..40 validates_length_of :email, :within => 3..100 validates_uniqueness_of :login, :email, :case_sensitive => false before_save :encrypt_password attr_accessible :login, :email, :password, :password_confirmation , :dni, :apellidos, :referencia, :nombre, :telefono, :avatar, :viaje_id def self.authenticate(login, password) u = find_by_login(login) u && u.authenticated?(password) ? u : nil end

Page 3: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

114

def self.encrypt(password, salt) Digest::SHA1.hexdigest("--#{salt}--#{password}--") end def encrypt(password) self.class.encrypt(password, salt) end def authenticated?(password) crypted_password == encrypt(password) end def remember_token?

remember_token_expires_at&&Time.now.utc< remember_token_expires_at end def remember_me remember_me_for 2.weeks end def remember_me_for(time) remember_me_until time.from_now.utc end def remember_me_until(time) self.remember_token_expires_at = time self.remember_token=encrypt("#{email}#{remember_token_expires_at}") save(false) end def forget_me self.remember_token_expires_at = nil self.remember_token = nil save(false) end protected # before filter def encrypt_password return if password.blank?

self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?

self.crypted_password = encrypt(password) end def password_required? crypted_password.blank? || !password.blank? end def encrypt_nombre Digest::SHA1.hexdigest(nombre) end end

Page 4: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

115

VIAJE require 'digest/sha1' class Viaje < ActiveRecord::Base validates_presence_of :nombre, :origen, :message=> "Al menos se necesita nombre y origen" belongs_to :admin has_many :ofertas, :order => 'suma DESC' has_many :destinos has_many :votos has_many :users def encrypt_nombre Digest::SHA1.hexdigest(nombre) end end

VOTO class Voto < ActiveRecord::Base belongs_to :user belongs_to :viaje belongs_to :oferta #validates_inclusion_of :valor, :in=>1..5, :message=>'Tu valoración debe ser entre 1 y 5' def after_create self.oferta.suma += self.valor #a la suma que teniamos le sumo el nuevo voto, esto ocurre justo despues de la creacion del voto self.oferta.save#se debe salvar en la base de datos si no, no se guarda end end

CONTROLADORES ACCOUNTSCONTROLLER class AccountsController < ApplicationController def index @accounts = Account.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @accounts } end end def show

Page 5: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

116

@account = Account.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @account }

end end def new @account = Account.new @accounts = Account.find(:all) respond_to do |format| format.html # new.html.erb format.xml { render :xml => [@account, @accounts] }

end end def edit @account = Account.find(params[:id]) end def create @account = Account.new(params[:account]) @accounts = Account.find(:all) respond_to do |format| if @account.save flash[:notice] = 'Tu cuenta ha sido creada con exito... ENTRA YA Y EMPIEZA A OFERTAR!!!.' format.html { redirect_to new_session_path } format.xml { render :xml => @account, :status => :created, :location => @account } else

flash[:notice] = 'Puede que no se halla podido guardar su cuenta por que el password no coincide'

format.html { render :action => "new" } format.xml { render :xml => @account.errors, :status => :unprocessable_entity } end end end def update @account = Account.find(params[:id]) respond_to do |format| if @account.update_attributes(params[:account]) flash[:notice] = 'Account was successfully updated.' format.html { redirect_to(@account) } format.xml { head :ok } else format.html { render :action => "edit" }

Page 6: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

117

format.xml { render :xml => @account.errors, :status => :unprocessable_entity } end end end def destroy @account = Account.find(params[:id]) @account.destroy respond_to do |format| format.html { redirect_to(accounts_url) } format.xml { head :ok } end end end

ADMINSCONTROLLER class AdminsController < ApplicationController def index @admins = Admin.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @admins } end end def show @admin = Admin.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @admin } end end def new @admin = Admin.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @admin } end end def edit

Page 7: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

118

@admin = Admin.find(params[:id]) end def create @admin = Admin.new(params[:admin]) respond_to do |format| if @admin.save flash[:notice] = 'Ya puedes crear tu viaje!!!.' format.html { redirect_to new_session_path } format.xml { render :xml => @admin, :status => :created, :location => @admin } else format.html { render :action => "new" } format.xml { render :xml => @admin.errors, :status => :unprocessable_entity } end end end def update @admin = Admin.find(params[:id]) respond_to do |format| if @admin.update_attributes(params[:admin]) flash[:notice] = 'Admin was successfully updated.' format.html { redirect_to(@admin) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @admin.errors, :status => :unprocessable_entity } end end end def destroy @admin = Admin.find(params[:id]) @admin.destroy respond_to do |format| format.html { redirect_to(admins_url) } format.xml { head :ok } end end end

Page 8: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

119

DESTINOSCONTROLLER class DestinosController < ApplicationController def index @destino = current_user.destino respond_to do |format| format.html # index.html.erb format.xml { render :xml => @destinos } end end def new end def create @destino = Destino.new(params[:destino]) @destino.user = current_user @destino.viaje_id = current_user.viaje_id respond_to do |format| if @destino.save #flash[:notice] = 'Destino creado!!!' format.html { redirect_to viaje_path(current_user.viaje_id)} format.xml { render :xml => @destino, :status => :created, :location => @destino } format.js { render :text => "<div class='destino'> destino elegido <br/><br/>#{@destino.lugar}</div>"} else format.html { render :action => "new" } format.xml { render :xml => @destino.errors, :status => :unprocessable_entity } end end end end

Page 9: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

120

EXPLICATIONSCONTROLLER class ExplicacionsController < ApplicationController def index respond_to do |format| format.html # index.html.erb format.xml { render :xml => @explicacions } end end def show respond_to do |format| format.html # show.html.erb format.xml { render :xml => @explicacion } end end end

OFERTASCONTROLLER class OfertasController < ApplicationController before_filter :load_viaje def index @ofertas = @viaje.ofertas.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @ofertas } end end def show @oferta = @viaje.ofertas.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @oferta } end end

Page 10: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

121

def load_viaje @viaje = Viaje.find(params[:viaje_id]) end end

SESSIONCONTROLLER def new end def create self.current_user = User.authenticate(params[:login], params[:password]) if logged_in? if params[:remember_me] == "1" self.current_user.remember_me cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at } end

#flash[:notice] = "Bienvenido. Úsuario desde: #{self.current_user.created_at}" redirect_to :controller=>'viajes', :action=>'show', :id=> self.current_user.viaje_id else flash[:notice] = "No estas en el sistema, crea una cuenta" render :action => 'new' end end def destroy self.current_user.forget_me if logged_in? cookies.delete :auth_token reset_session flash[:notice] = "You have been logged out." redirect_back_or_default('/viajes') end end

USERSCONTROLLER class UsersController < ApplicationController include AuthenticatedSystem def new

Page 11: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

122

flash[:notice] = "Registrate para acceder a tu viaje!!!! " end def create cookies.delete :auth_token @user = User.new(params[:user]) (@ref1, @ref2)[email protected]('-') @si=Viaje.find_by_id(@ref1) if(@si.encrypt_nombre[0..2][email protected]_nombre[-3..-1]==@ref2) @user.viaje_id = @si.id @user.save if @user.errors.empty? self.current_user = @user redirect_to :controller=>'explicacions' flash[:notice] = "Tu cuenta ha sido creada" else render :action => 'new' end else flash[:notice] = "Lo sentimos, pero su referencia es erronea" render :action => 'new' end end end

VIAJESCONTROLLER class ViajesController < ApplicationController before_filter :login_required def index @viajes = Viaje.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @viajes } end end def show

Page 12: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

123

@viaje = Viaje.find(params[:id]) @ofertas = @viaje.ofertas.paginate(:page => params[:page], :per_page =>5)#hace la paginacion, el numero que sacara por pagina está definido en el modelo @numusu = @viaje.users.count @usuarios [email protected](:page => params[:page2], :per_page =>6) respond_to do |format| format.html # show.html.erb format.xml { render :xml => [@viaje, @numusu, @ofertas, @usuarios] } end end end

VOTOSCONTROLLER class VotosController < ApplicationController def index @votos = @oferta.votos.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @votos } end end def new end def create @viaje=Viaje.find(current_user.viaje_id) @voto = Voto.new(params[:voto]) @voto.viaje_id = current_user.viaje_id @voto.user_id = current_user.id @voto.oferta_id =params[:oid] @voto.valor = params[:cuanto] respond_to do |format| if @voto.save #flash[:notice] = 'Voto creado!!!!' format.html { redirect_to viaje_path(current_user.viaje_id) } format.xml { render :xml => @voto, :status => :created, :location => @voto } format.js { render :update do |page|

Page 13: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

124

@ofertas = @viaje.ofertas.paginate(:page => params[:page], :per_page=>5) page.replace_html('ofer', :partial => 'viajes/oferta',:collection => @ofertas) end } else format.html { render :action => "new" } format.xml { render :xml => @voto.errors, :status => :unprocessable_entity } end end end end

Vistas ACCOUNTS Edit <h1>Editing account</h1> <%= error_messages_for :account %> (@account, :html=>{:multipart=>true}) <% form_for(@account, :html=>{:multipart=>true}) do |f| %> <p> <b>Login</b><br /> <%= f.text_field :login %> </p> <p> <b>Password</b><br /> <%= f.password_field :password %> </p> <p> <b>Nombre de la agencia</b><br /> <%= f.text_field :nombreagencia %> </p> <p> <b>Ciudad de la agencia</b><br /> <%= f.text_field :ciudadagencia %> </p> <p> <b>Nombre del responsable</b><br /> <%= f.text_field :nombreresponsable %> </p>

Page 14: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

125

<p> <b>Email de contacto</b><br /> <%= f.text_field :emailagencia %> </p> <p> <b>Telefono de contacto</b><br /> <%= f.text_field :telefonoagencia %> </p> <p> <b>Web</b><br /> <%= f.text_field :webagencia %> </p> <p> <b>Web</b><br /> <%= file_column_field "account", "avatar" %> </p> <p> <%= f.submit "Update" %> </p> <% end %> <%= link_to 'Show', @account %> | <%= link_to 'Back', accounts_path %>

New <div id="main"> <!-- main table --> <br/><br/><br/> <div class="tablebox"> <h1>Crea tu nueva cuenta!!!</h1> <%= error_messages_for :account %> <% form_for(@account, :html=>{:multipart=>true}) do |f| %> <p> <b>LOGIN</b><br /> <%= f.text_field :login %> </p> <p> <b>PASSWORD</b><br /> <%= f.password_field :password %> </p> <p> <b>CONFIRME SU PASSWORD</b><br /> <%= f.password_field :conf_pass %> </p> <p> <b>NOMBRE DE LA AGENCIA</b><br /> <%= f.text_field :nombreagencia %> </p>

Page 15: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

126

<p> <b>CIUDAD</b><br /> <%= f.text_field :ciudadagencia %> </p> <p> <b>EMAIL DE CONTACTO</b><br /> <%= f.text_field :emailagencia %> </p> <p> <b>TELEFONO DE CONTACTO</b><br /> <%= f.text_field :telefonoagencia %> </p> <p> <b>WEB</b><br /> <%= f.text_field :webagencia %> </p> <p> <b>IMAGEN CORPORATIVA</b><br /> <%= file_column_field "account", "avatar" %> </p> <p> <%= f.submit "Crear" %> </p> <% end %> </div> <div class="lalala2"></div> <div class="footer"><h2>Otras agencias ya inscritas al sistema!!!</h2></div> <% for account in @accounts %> <tr> <td> <% unless account.avatar.nil? %> <%= image_tag url_for_file_column(account, :avatar)%> </td> </tr> <%end%> <% end %> <div class="enlace"> <%= link_to 'Vuelve a la pagina inicial', new_session_path %></div> </div>

Page 16: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

127

Show <p> <b>Login:</b> <%=h @account.login %> </p> <p> <b>Nombre:</b> <%=h @account.nombreagencia %> </p> <p> <b>Ciudad:</b> <%=h @account.ciudadagencia %> </p> <p> <b>Web:</b> <%=h @account.webagencia %> </p> <p> <b>Email:</b> <%=h @account.emailagencia %> </p> <% unless @account.avatar.nil? %> <p> </p> <%= image_tag url_for_file_column(@account, :avatar)%> <%end%> <%= link_to 'Back', accounts_path %>

Index <h1>Cuentas de agencias creadas</h1> <table> <tr> <th>Agencia</th> <th>Ciudad</th> <th>Imagen</th> </tr> <% for account in @accounts %> <tr> <td><%=h account.login %></td>

Page 17: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

128

<td><%=h account.ciudadagencia %></td> <td> <% unless account.avatar.nil? %> <p> </p> <%= image_tag url_for_file_column(account, :avatar)%> <%end%></td> </tr> <% end %> </table> <br /> <%= link_to 'Crear nueva cuenta', new_account_path %> <br /> <%= link_to 'Vuelve a la pagina inicial y busca a tus clientes', viajes_path %>

ADMIN/VIAJES Edit <div id="main"> <div class="tablebox"> <h1>CAMBIA TUS DATOS</h1> <%= error_messages_for :viaje %> <% form_for([:admin, @viaje]) do |f| %> <p> <b>NOMBRE</b><br /> <%= f.text_field :nombre %> </p> <p> <b>ORIGEN</b><br /> <%= f.text_field :origen %> </p> <p> <b>ULTIMO IDA PARA VOTAR</b><br /> <%= f.text_field :f_fin %> </p> <br/> <p> <%= f.submit "Actualizar" %> </p> <% end %> <div class="enlace"> <%= link_to 'Ir a la página principal', new_session_path %> </div> </div> <div class="lalala2"></div>

Page 18: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

129

</div>

New <div id="main"> <!-- main table --> <br/><br/><br/> <div class="tablebox"> <h1>VAMOS <%=h @admin.login %> CREA UN VIAJE PARA TUS AMIGOS!!!!</h1> <br/> <%= error_messages_for :viaje %> <% form_for([:admin, @viaje]) do |f| %> <p> <b>NOMBRE CON EL QUE QUIERAS LLAMAR AL VIAJE</b><br /> <%= f.text_field :nombre %> </p> <p> <b> CIUDAD DE LA UNIVERSIDAD, INSTITUTO, COLEGIO...</b><br /> <%= f.text_field :universidad %> </p> <p> <b>ESTUDIOS</b><br /> <%= f.text_field :estudios %> </p> <p> <b>QUIERES SALIR DE ALGUNA CIUDAD ESPECIFICA? CUAL/CUALES??</b><br /> <%= f.text_field :origen %> </p> <p> <b>ULTIMO DIA PARA VOTAR LAS OFERTAS DE LAS AGENCIAS</b><br /> <%= calendar_date_select_tag "viaje[f_fin]", nil , :year_range => [2007, 2012]%> <!id es viaje[f_fin] </p> </p> <br/> <p> <%= f.submit "Crear Viaje" %> </p> <% end %> <br/><br/> <div class="enlace"

Page 19: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

130

<%= link_to 'Volver a la página inicial y crearlo mas tarde', new_session_path %> </div> </div> <div class="lalala2"></div> </div>

Show <div id="main"> <br/><br/> <div class="tablebox"> <h1> Caracteristicas del viaje </h1> <div class="enlace"> <br/> <p> <b>Nombre:</b> <%=h @viaje.nombre %> </p> <br/> <p> <b>Origen:</b> <%=h @viaje.origen %> </p> <br/> <p> <b>Fecha fin votación:</b> <%=h @viaje.f_fin %> </p> <br/> <p> <b> Referencia para que tus compañeros se apunten a tu viaje creado:</b> <div class="referencia"> <br/><%=h @viaje.id%>-<%=h @viaje.encrypt_nombre[0..2] %> <%=h @viaje.encrypt_nombre[-3..-1] %> </div> </p> <% unless @viaje.ofertas.empty? %> <p> </p> <br/> <h2>Ofertas para este viaje ya propuestas: <%[email protected]%></h2> <% end %> <br/> <%= link_to 'Quieres cambiar algo antes de guardarlo?', edit_admin_viaje_path(@viaje) %> | <%= link_to 'Ir a la página principal', new_session_path %> </div> </div> <div class="lalala2"></div> </div>

Page 20: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

131

Index h1>VIAJES YA CREADOS POR OTROS USUARIOS</h1> <table> <tr> <th>Nombre </th> <th>Origen </th> <th>Fecha inicio </th> <th>Fecha fin </th> <th>Fecha votar destino </th> <th>Fecha votar viaje </th> <th>Admin </th> </tr> <% for viaje in @viajes %> <tr> <td><%=h viaje.nombre %></td> <td><%=h viaje.origen %></td> <td><%=h viaje.f_inicio %></td> <td><%=h viaje.f_fin %></td> <td><%=h viaje.adni %></td> </tr> <% end %> </table> <br /> <%= link_to 'Crear nuevo Viaje', new_admin_viaje_path %> <br /> <%= link_to 'Volver a lista de viajes', viajes_path %>

ADMINS Edit <h1>Editing admin</h1> <%= error_messages_for :admin %> <% form_for(@admin) do |f| %> <p> <b>Login</b><br /> <%= f.text_field :login %> </p> <p> <b>Password</b><br /> <%= f.text_field :password %> </p> <p> <%= f.submit "Update" %> </p> <% end %>

Page 21: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

132

<%= link_to 'Show', @admin %> | <%= link_to 'Back', admins_path %>

New <div id="main"> <br/><br/><br/> <div class="tablebox"> <h1>EMPIEZA TU VIAJE REGISTRANDOTE COMO ADMINISTADOR</h1><br/> <%= error_messages_for :admin %> <% form_for(@admin) do |f| %> <p> <b>LOGIN</b><br /> <%= f.text_field :login %> </p> <p> <b>PASSWORD</b><br /> <%= f.text_field :password %> </p> <p> <b>TELÉFONO DE CONTACTO</b><br /> <%= f.text_field :telefono %> </p> <br/> <p> <%= f.submit "Listo!!" %> </p> <% end %> <div class="enlace"><%= link_to 'Vuelve a la pagina inicial', new_session_path %></div> </div> <div class="lalala2"></div> </div>

Show <p> <b>Login:</b> <%=h @admin.login %> </p> <p> <b>Password:</b> <%=h @admin.password %> </p> <%= link_to 'Edit', edit_admin_path(@admin) %> | <%= link_to 'Back', admins_path %>

Page 22: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

133

Index <h1>VIAJES YA CREADOS POR OTROS USUARIOS</h1> <table> <tr> <th>Nombre </th> <th>Origen </th> <th>Fecha inicio </th> <th>Fecha fin </th> <th>Fecha votar destino </th> <th>Fecha votar viaje </th> <th>Admin </th> </tr> <% for viaje in @viajes %> <tr> <td><%=h viaje.nombre %></td> <td><%=h viaje.origen %></td> <td><%=h viaje.f_inicio %></td> <td><%=h viaje.f_fin %></td> <td><%=h viaje.adni %></td> </tr> <% end %> </table> <br /> <%= link_to 'Crear nuevo Viaje', new_admin_viaje_path %> <br /> <%= link_to 'Volver a lista de viajes', viajes_path %>

AGENCIA AGENCIA/ACCOUNTS Edit <h1>Edite su cuenta</h1> <%= error_messages_for :account %> <% form_for([:agencia, @account], :html=>{:multipart=>true}) do |f| %> <p> <b>Nombre de la agencia</b><br />

Page 23: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

134

<%= f.text_field :nombreagencia %> </p> <p> <b>Ciudad de la agencia</b><br /> <%= f.text_field :ciudadagencia %> </p> <p> <b>Nombre del responsable</b><br /> <%= f.text_field :nombreresponsable %> </p> <p> <b>Email de contacto</b><br /> <%= f.text_field :emailagencia %> </p> <p> <b>Telefono de contacto</b><br /> <%= f.text_field :telefonoagencia %> </p> <p> <b>Web</b><br /> <%= f.text_field :webagencia %> </p> <p> <b>Web</b><br /> <%= file_column_field "account", "avatar" %> </p> <p> <%= f.submit "Update" %> </p> <% end %>

Show <p> <b>Login:</b> <%=h @account.login %> </p> <p> <b>Nombre:</b> <%=h @account.nombreagencia %> </p> <p> <b>Ciudad:</b> <%=h @account.ciudadagencia %> </p> <p>

Page 24: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

135

<b>Web:</b> <%=h @account.webagencia %> </p> <p> <b>Email:</b> <%=h @account.emailagencia %> </p> <%= image_tag url_for_file_column(@account, :avatar)%>

AGENCIA/OFERTAS New <div id="main"> <div class="tablebox"> <h1>Nueva oferta</h1> <h2>Una vez creada la oferta será dada de alta de inmediato para ser votada</h2> <%= error_messages_for :oferta %> <% form_for([:agencia, @viaje, @oferta]) do |f|%> <p> <b>LOGIN DE SU AGENCIA</b><br /> <h2><%=h @oferta.account.login %></h2> </p> <p> <b>ORIGEN</b><br /> <%= f.text_field :origen %> </p> <p> <b>DESTINO</b><br /> <%= f.text_field :destino %> </p> <p> <b>FECHA INICIO VIAJE</b><br /> <%= calendar_date_select_tag "oferta[f_inicio]", nil , :year_range => [2007, 2012]%> </p> <p> <b>FECHA FIN VIAJE</b><br /> <%= calendar_date_select_tag "oferta[f_fin]", nil , :year_range => [2007, 2012]%> </p> <p> <b>PRECIO</b><br /> <%= f.text_field :precio %>

Page 25: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

136

</p> <p> <b>ALGUN COMENTARIO?</b><br /> <%= f.text_field :comentario %> </p> <br/> <%= f.submit "Crear oferta!" %> <%end%> <div class="enlace"> <%= link_to 'Ofertar luego', ([:agencia, @viaje]) %> </div> </div> <div class="lalala2"></div> </div>

Edit <p> <b>Login de la agencia:</b> <%=h @oferta.account.login %> </p> <p> <b>Fecha inicio viaje ofertado:</b> <%=h @oferta.f_inicio %> </p> <p> <b>Fecha fin viaje ofertado:</b> <%=h @oferta.f_fin %> </p> <p> <b>Origen:</b> <%=h @oferta.origen %> </p> <p> <b>Destino:</b> <%=h @oferta.destino %> </p> <p> <b>Precio:</b> <%=h @oferta.precio %> </p> <p> <b>Comentario:</b> <%=h @oferta.comentario %> </p> | <%= link_to 'Volver', agencia_viaje_ofertas_path(@viaje) %>

Page 26: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

137

Index <div id="main"> <h1>Mostrando ofertas para este viaje</h1> <table> <tr> <th>login agencia</th> <th>Fecha fin votaciones</th> <th>Origen</th> <th>Destino</th> <th>Precio</th> <th>Comentario</th> </tr> <% for oferta in @ofertas %> <tr> <td><%=h oferta.account.login %></td> <td><%=h oferta.f_fin %></td> <td><%=h oferta.origen %></td> <td><%=h oferta.destino %></td> <td><%=h oferta.precio %></td> <td><%=h oferta.comentario %></td> <td><%= link_to 'Mostrar', [:agencia, @viaje, oferta] %></td> </tr> <% end %> </table> <br /> <%= link_to 'Volver a viaje', ([:agencia, @viaje]) %> <%= link_to 'Crear una nueva oferta', new_agencia_viaje_oferta_path(@viaje) %> </div>

AGENCIA/VIAJES Show <div class="tela"> <p><strong>Bienvenido <%=h @account.login %></strong></p> <% unless @account.avatar.nil? %> <p> </p> <%= image_tag url_for_file_column(@account, :avatar)%> <%end%> <%= link_to "Logout", viajes_path %>

Page 27: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

138

</div> <div id="main"> <br/><br/><br/><br/><h1> Caracteristicas del viaje </h1> <h2> <p> <b>Nombre:</b> <%=h @viaje.nombre %> </p> <p> <b>Origen:</b> <%=h @viaje.origen %> </p> <p> <b>Fecha fin para votar:</b> <%=h @viaje.f_fin %> </p> </h2> <% if @viaje.destinos.empty?%> <h2> Aun no hay ningun destino propuesto para ofertar</h2> <%end%> <% unless @viaje.destinos.empty? %> <p> </p> <br/> <h1>Destinos y observaciones de los usuarios</h1> <table border="3"> <tr> <th>DESTINO</th> <th>OBSERVACIONES</th> </tr> <% @desti.each do |destino|%> <tr> <td><%=h destino.lugar %></td> <td><%=h destino.observaciones %></td> </tr> <% end %> </table> <% end %> <h2><%= will_paginate @desti, :param_name=>:page2%></h2> <% unless @viaje.ofertas.empty? %> <p> </p> <br/> <h1>Ofertas para este viaje ya propuestas</h1> <table border="1"> <tr>

Page 28: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

139

<th>DESTINO</th> <th>PRECIO</th> <th>COMENTARIOS</th> <th>LOGIN AGENCIA OFERTANTE</th> <th>VOTOS POSITIVOS!!! </tr> <% @ofertas.each do |oferta|%> <tr> <td><%=h oferta.destino %></td> <td><%=h oferta.precio %></td> <td><%=h oferta.comentario %></td> <%if [email protected] %> <td>ES TUYA!!!</td> <%else%> <td><%=h oferta.account.login %></td> <%end%> <td><%=h oferta.suma %> </tr> <% end %> </table> <h2><%= will_paginate @ofertas%></h2> <% end %> <% unless @viaje.destinos.empty?%> <div class="enlace"> <%= link_to "Hacer una oferta para este viaje", new_agencia_viaje_oferta_path(@viaje) %> <%end%> <%= link_to "Buscar otros viajes para ofertar", agencia_viajes_path %> </div>

Index <div class="tela"> <p><strong>Bienvenido <%=h @account.login %></strong></p> <% unless @account.avatar.nil? %> <p> </p> <%= image_tag url_for_file_column(@account, :avatar)%> <%end%> <%= link_to "Logout", viajes_path %> </div> <div id="main"> <br/><br/><br/><br/><br/><br/> <h1>Lista de Viajes en el sistema</h1> <table border="2"> <tr> <th>NOMBRE </th> <th>UNIVERSIDAD </th>

Page 29: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

140

<th>VIAJEROS YA UNIDOS! </th> <th>ULTIMO DIA PARA VOTAR SUS OFERTAS </th> <th>ESTADO DEL VIAJE</th> </tr> <% for viaje in @viajes %> <tr> <td><%=h viaje.nombre %></td> <td><%=h viaje.universidad %></td> <td><%= viaje.users.count%> <td><%=h viaje.f_fin %></td> <% unless viaje.destinos.empty?%> <td><%= link_to 'Mostrar destinos propuestos y hacer una oferta', [:agencia, viaje] %></td> <%end%> <% if viaje.destinos.empty?%> <td> El viaje aun no tiene ningun destino propuesto para ofertar</td> <%end%> </tr> <% end %> </table> <h2><%= will_paginate @viajes%></h2> <div id="aki"> <%= link_to_function("Edita tu cuenta", "$('form_cuenta').appear()") %> <div id="form_cuenta" style="display:none;" > <% form_remote_for([:agencia, @account], :update => 'aki') do |f| %> <br /> <p> <b>Nombre de la agencia</b><br /> <%= f.text_field :nombreagencia %> </p> <p> <b>Ciudad de la agencia</b><br /> <%= f.text_field :ciudadagencia %> </p> <p> <b>Nombre del responsable</b><br /> <%= f.text_field :nombreresponsable %> </p> <p> <b>Email de contacto</b><br />

Page 30: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

141

<%= f.text_field :emailagencia %> </p> <p> <b>Telefono de contacto</b><br /> <%= f.text_field :telefonoagencia %> </p> <p> <b>Web</b><br /> <%= f.text_field :webagencia %> </p> <br /> <p> <%= f.submit "Update" %> </p> <% end %> </div> </div> <br /> <br /> <div class="footer"><h2>Otras agencias ya inscritas al sistema!!!</h2></div> <% for account in @accounts %> <tr> <td> <% unless account.avatar.nil? %> <%= image_tag url_for_file_column(account, :avatar)%> </td> </tr> <%end%> <% end %> <h2><%= will_paginate @accounts, :param_name=>:page2%></h2>

DESTINOS New <h1>Nuevo destino</h1> <%= error_messages_for :destino %> <% form_for :destino, :url => destinos_path do |f| %> <p> <b>Lugar</b><br /> <%= f.text_field :lugar %> </p>

Page 31: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

142

<p> <b></b><br /> <%= f.text_area :observaciones %> </p> <p> <%= f.submit "Create" %> </p> <% end %>

Show <p> <b>Body:</b> <%=h @destino.lugar %> </p> <%= link_to 'Edit', [:edit, @user, @destino] %> | <%= link_to 'Back', user_destinos_path(@user) %>

Index <h1>Destino creado</h1> <td><%=h @destino.lugar %></td> <td><%=h @destino.observaciones%>

EXPLICACIONS Index <div id="main"> <!-- main table --> <br/><br/><br/> <div class="tablebox"> <br/> <h1>Que como funciona esto?</h1> <p> <h2> Estas preparado????????</h2></p><br/><br/> <p> <h2> 1º Propon un destino</h2></p><br/><br/><br/>

Page 32: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

143

<p> <h2> 2º Vota las ofertas propuestas por las agencias para los destinos de todos los usuarios de tu viaje y CONÓCELOS</h2></p><br/><br/><br/> <p> <h2> 3º Tendras hasta el dia <%= Viaje.find(current_user.viaje_id).f_fin%> para votar todas y encontrar la mejor oferta segun tu grupo </h2></p><br/><br/><br/> <h2><%= link_to "Ir ya a mi viaje!!", :controller=>'viajes', :action=>'show', :id=> current_user.viaje_id %></h2> </div> </div>

OFERTAS _Oferta <% form_for([@viaje, @oferta]) do |f|%> <p> <b>Login agencia</b><br /> <%= f.text_field :loginagencia %> </p> <p> <b>Fecha inicio</b><br /> <%= f.text_field :f_inicio %> </p> <p> <b>Fecha fin</b><br /> <%= f.text_field :f_fin %> </p> <p> <b>Origen</b><br /> <%= f.text_field :origen %> </p> <p> <b>Destino</b><br /> <%= f.text_field :destino %> </p> <p> <b>Precio</b><br /> <%= f.text_field :precio %> </p> <p> <b>Comentario</b><br /> <%= f.text_area :comentario %> </p> <%= f.submit button_name %> <%end%>

Page 33: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

144

Edit <%= error_messages_for :oferta %> <%= render :partial => @oferta, :locals => { :button_name => "Actualizar"} %> <%= link_to 'Mostrar', [@viaje, @oferta] %> | <%= link_to 'Volver', viaje_ofertas_path(@oferta) %>

New <h1>Nueva oferta</h1> <%= error_messages_for :oferta %> <%= render :partial => @oferta, :locals => { :button_name => "Crear"} %> <%= link_to 'Volver', viaje_ofertas_path(@viaje) %>

Show <p> <b>Login de la agencia:</b> <%=h @oferta.loginagencia %> </p> <p> <b>Fecha inicio:</b> <%=h @oferta.f_inicio %> </p> <p> <b>Fecha fin:</b> <%=h @oferta.f_fin %> </p> <p> <b>Origen:</b> <%=h @oferta.origen %> </p> <p> <b>Destino:</b> <%=h @oferta.destino %> </p> <p> <b>Precio:</b> <%=h @oferta.precio %> </p> <p>

Page 34: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

145

<b>Comentario:</b> <%=h @oferta.comentario %> </p> <%= link_to 'Editar', [:edit, @viaje, @oferta] %> | <%= link_to 'Volver', viaje_ofertas_path(@viaje) %>

Index <h1>Mostrando ofertas para este viaje</h1> <table> <tr> <th>Fecha inicio</th> <th>Fecha fin</th> <th>Origen</th> <th>Destino</th> <th>Precio</th> <th>Comentario</th> </tr> <% for oferta in @ofertas %> <tr> <td><%=h oferta.f_inicio %></td> <td><%=h oferta.f_fin %></td> <td><%=h oferta.origen %></td> <td><%=h oferta.destino %></td> <td><%=h oferta.precio %></td> <td><%=h oferta.comentario %></td> <td><%= link_to 'Mostrar', [@viaje, oferta] %></td> <td><%= link_to 'Editar', [:edit, @viaje, oferta] %></td> <td><%= link_to 'Destruir', [@viaje, oferta], :confirm => "¿Seguro que quieres borrar la oferta con origen #{oferta.origen}? ", :method => :delete %></td> </tr> <% end %> </table> <br /> <%= link_to 'Volver a viaje', @viaje %> <%= link_to 'Crear una nueva oferta', new_viaje_oferta_path(@viaje) %>

SESSION New <!-- formbox --> <% form_tag session_path do -%>

<div class="formbox"> <label class="nombre" for="nombre-string">Nombre</label> <span><%= text_field_tag 'login', nil, {:id => 'nombre-string'} %></span> <label class="clave" for="clave-string">Clave</label>

Page 35: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

146

<span><%= password_field_tag 'password', nil, : id => 'clave-string' %></span> <%= image_submit_tag('submit.gif', :class => 'submit') %>

</div> <% end -%> <!-- <img src="/images/column-img.png" alt="Accede a tu cuenta"/>--> <%= image_tag 'column-img.png', :alt => "Accede a tu cuenta" %>

USERS New <div id="main"> <!-- main table --> <br/><br/><br/> <div class="tablebox"> <%= error_messages_for :user %> <% form_for :user, :url => users_path, :html =>{:multipart=>true} do |f| -%> <br/> <p><label for="nombre">NOMBRE</label><br/> <%= f.text_field :nombre %></p> <p><label for="apellidos">APELLIDOS</label><br/> <%= f.text_field :apellidos %></p> <p><label for="referencia">REFERENCIA VIAJE (Pon aqui la referencia que te han dado)</label><br/> <%= f.text_field :referencia %></p> <p><label for="telefono">TELEFONO</label><br/> <%= f.text_field :telefono %></p> <p><label for="login">LOGIN</label><br/> <%= f.text_field :login %></p> <p><label for="email">E-MAIL</label><br/> <%= f.text_field :email %></p> <p><label for="password">PASSWORD</label><br/> <%= f.password_field :password %></p> <p><label for="password_confirmation">CONFIRMA PASSWORD</label><br/> <%= f.password_field :password_confirmation %></p> <p><label for="avatar">IMAGEN PARA MOSTRAR AL RESTO DE TUS COMPAÑEROS</label><br/> <%= file_column_field "user", "avatar" %>

Page 36: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

147

</p> <br/> <p><%= submit_tag 'Sign up' %></p> <% end -%> <div class="lalala2"></div> </div> </div>

VIAJES _Oferta <% oid ||= oferta.id %> <tr> <td><%=h oferta.destino%></td> <td><%=h oferta.precio %></td> <td><%=h oferta.account.login %></td> <td><%=h oferta.comentario %></td> <td><%=h oferta.suma %></td> <% if oferta.votos.find_by_user_id(current_user.id) %> <td>tu voto : <%=h oferta.votos.find_by_user_id(current_user.id).valor %></td> <%end%> <% unless oferta.votos.find_by_user_id(current_user.id) %> <td class="vota"> <div class="vota"><%= link_to_function("Vota ya!!!", "$('form_voto#{oid}').appear();$('sisi#{oid}').puff()", :id => "sisi#{oid}") %></div> <div id="form_voto<%= oid %>" style="display:none;"> <% form_remote_for :voto, :url => votos_path do |f| %> <%= hidden_field_tag :oid, oid %> <select name = "cuanto"> <option value="1">1 voto</option> <option value="2">2 votos</option> <option value="3">3 votos</option> </select> <%= f.submit "OK" %> <%end%> </div> </td> <%end%>

Page 37: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

148

</tr>

Show <div class="avatar"> <div class="sub-avatar"> <strong class="avatar-top">Bienvenido:</strong>

<div class="nombre"> <%=h @current_user.login%></div> </div> <% unless @current_user.avatar.nil? %> <p> </p> <%= image_tag url_for_file_column(@current_user, :avatar)%> <%else%>

<img src="/images/SIN.gif" alt=""/> <%end%> <div class="nombre"><%=h @current_user.login%></div> <div id="oo"> <% unless @current_user.destino %> <strong class="avatar-bottom">¿Aún no elegiste destino?</strong> <div id="aki" class="popup-display"><a id="popup-display" href="#">¡Elijelo YA!</a></div> <%end%> </div> <%if @current_user.destino%> <div class="destino"> Tu destino propuesto:</div> <div class="destino2"> <%=h @current_user.destino.lugar%> </div> <%end%> </div> <%= link_to('Logout', logout_path , :class=>"desconectar")%> <!-- popup box --> <div class="popup" id="popup"> <% form_remote_for :destino, :url => destinos_path, :update => 'oo' do |f| %> <div> <a class="close" href="#" id="popup-close">close</a> <span class="head-1">Destino</span> <%= f.text_field :lugar, {:class => "string"} %> <span class="head-2">Observaciones (Max 50 caracteres)</span> <%= f.text_area :observaciones, {:cols => "10", :rows=>"5"} %> <input class="popup-submit" type="image" src="/images/popup-submit.gif" onclick ="$('popup').hide();"/> </div> <%end%>

Page 38: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

149

</div> <div id="main"> <!-- main table --> <div class="footer"><h2>OFERTAS DE AGENCIAS PARA:</h2><h3><%[email protected]%>.<%[email protected]%></h3></div> <div class="tablebox"> <table cellpadding="0" cellspacing="0"> <tr class="theader"> <td class="destino">Destino</td> <td class="precio">Precio</td> <td class="login">Login</td> <td class="caracteristicas">Caracteristicas</td> <td class="votos">Votos Positivos</td> <td class="dale">¡Dale tu voto!</td> </tr> <tbody id="ofer"> <% @ofertas.each do |oferta|%> <%= render :partial => 'oferta', :locals => {:oferta =>oferta, :oid =>oferta.id, :button_name => "Create"} %> <%end%> </tbody> </table> <div class="footer"> <h3>ULTIMO DIA PARA VOTAR :<%= @viaje.f_fin%></h3> </div> </div> <div class="footer"> <h3><%= will_paginate @ofertas%></h3> </div> <!-- gallery --> <br/> <div class="gallery"> <h2>¡Tus compañeros de viaje!</h2> <div class="soisya"> ¡Sois ya <%= @viaje.users.count%> usuarios...<bh/>CONÓCELOS!! </div> <% @usuarios.each do |user|%> <% unless user == current_user %> <div class="sub-gallery"> <ul> <% unless user.avatar.nil?%> <li><%= image_tag url_for_file_column(user, :avatar)%></li> <%else%> <li><img src="/images/SIN.gif" alt=""/> <%end%> <%if user.destino%>

Page 39: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

150

<li> <tr><h3>LOGIN:<%= user.login%></h3></tr> <tr><h3>DESTINO:<%=h user.destino.lugar%> </h3></tr></li> <%else%> <li> <tr><h3>LOGIN:<%= user.login%></h3></tr> <tr><h3>DESTINO: ?</h3></tr> </li> <%end%> </ul> </div> <%end%> <%end%> </div> </div> <h2><%= will_paginate @usuarios, :param_name=>:page2%></h2>

Index <h1>Lista de Viajes en el sistema</h1> <% if logged_in? %> <p><strong>Bienvenido <%=h current_user.login %></strong></p> <p><%= link_to 'Logout', logout_path %></p> <% else %> <p><strong>You are currently not logged in.</strong></p> <p> <%= link_to 'Login', login_path %> or <%= link_to 'Sign Up', signup_path %> </p> <% end %> <table> <tr> <th>Nombre </th> <th>Origen </th> <th>Fecha inicio votación </th> <th>Fecha fin votación </th> <th>Admin(dni) </th> </tr> <% for viaje in @viajes %> <tr> <td><%=h viaje.nombre %></td> <td><%=h viaje.origen %></td> <td><%=h viaje.f_inicio %></td>

Page 40: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

151

<td><%=h viaje.f_fin %></td> < <td><%=h viaje.adni %></td> </tr> <% end %> </table> <br /> <%= link_to 'Soy Administrador', admin_viajes_path %> <%= link_to 'Soy una Agencia', agencia_viajes_path %> <br /> <br /> <%= link_to 'Agencia, ¿Aun no tienes tu cuenta?, Hazte una aqui', accounts_path%> <br /> <%= link_to 'Este link es para agregar cuenta de administradores', admins_path%>

VOTOS Edit <%= error_messages_for :voto %> <% form_for(@oferta,@voto) do |f| %> <p> <b>Decimal</b><br /> <%= f.text_field :valor %> </p> <p> <%= f.submit "Update" %> </p> <% end %> <%= link_to 'Show', @voto %> | <%= link_to 'Back', votos_path %>

New <h1>VOTA ESTA OFERTA</h1> <%= error_messages_for :voto %> <% form_for :voto, :url => votos_path do |f| %> <p> <b>Dale una puntuación del 1 al 5!!!!!!</b><br />

Page 41: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

152

<%= hidden_field_tag :oid, params[:oid] %> <%= f.text_field :valor %> </p> <p> <%= f.submit "Create" %> </p> <% end %>

Show <p> <b>Decimal:</b> <%=h @voto.valor %> </p> <%= link_to 'Edit', edit_voto_path(@voto) %> | <%= link_to 'Back', votos_path %>

Index <table> <tr> <th>Votos</th> </tr> <% for voto in @votos %> <tr> <td><%=h voto.valor %></td> <td><%= link_to 'Show', voto %></td> <td><%= link_to 'Edit', edit_voto_path(voto) %></td> <td><%= link_to 'Destroy', voto, :confirm => 'Are you sure?', :method => :delete %></td> </tr> <% end %> </table> <br /> <%= link_to 'New voto', new_voto_path %>

LAYOUTS Applications-Destinos-Sessions-Users-Viajes-Votos <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Quenospiramos</title> <%= stylesheet_link_tag 'all' %> <%= javascript_include_tag :defaults %>

Page 42: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

153

<%= calendar_date_select_includes "blue" %> <p style="color: #ff0000; font-size: 16px; text-align: center;"><%= flash[:notice] %></p> <!--[if lt IE 7]><link rel="stylesheet" type="text/css" href="css/ie.css" media="screen"/><![endif]--> </head> <body> <!-- header part --> <div id="header"> <!-- logo --> <strong class="logo"><a href="#">quenospiramos.com</a></strong> <%= yield :layout %> <!-- footer part --> <div class="footer">quenospiramos &copy; 2008 - Condiciones y Terminos de uso - Politica de privacidad - Ayuda y Contacto</div> </div> </body> </html>

Sessions <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Quenospiramos</title> <%= stylesheet_link_tag 'all' %> <%= javascript_include_tag 'js/ie-png' %> <p style="color: #ff0000; font-size: 10px; text-align: center;"><%= flash[:notice] %></p> <!--[if lt IE 7]><link rel="stylesheet" type="text/css" href="css/ie.css" media="screen"/><![endif]--> </head> <body class="index"> <!-- header part --> <div id="header"> <strong class="logo"><a href="#">quenospiramos.com</a></strong> <div class="entar"> <span>¿Eres Agencia?</span> <div><%= link_to '', agencia_viajes_path%></div> </div> <div class="registrate"><%= link_to 'Estas ya registrada?? ', new_account_path%></div> </div> <!-- main part --> <div id="main"> <!-- left column --> <div class="column"> <%= yield :layout %>

Page 43: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

154

</div> <!-- content part --> <div class="content"> <div class="unete"> <h1>¡Únete!</h1> <p>Crea un viaje o únete al que más te guste, conoce a gente, haz nuevos amigos, añade destinos, organiza fechas, elije alojamiento...</p> <strong>y cómete el mundo!</strong> </div> <div class="part-1"><div><%= link_to '', signup_path%></div></div> <div class="part-2"> <%= link_to '', new_admin_viaje_path%></div> <div class="registrate"> <div><%= link_to 'Pero registrate antes como administrador!!', new_admin_path%></div> </div> <!-- footer part --> <div class="footer">quenospiramos &copy; 2008 - Condiciones y Terminos de uso - Politica de privacidad - Ayuda y Contacto</div> </div> </div> </body> </html>

CONFIG

Database defaults: &defaults adapter: mysql encoding: utf8 username: root password: decide socket: /var/run/mysqld/mysqld.sock development: database: viajes_beta3_development <<: *defaults test: database: viajes_beta3_test <<: *defaults production: database: viajes_beta3_production <<: *default

Page 44: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

155

Boot (no se debe de cambiar) RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT) module Rails class << self def boot! unless booted? preinitialize pick_boot.run end end def booted? defined? Rails::Initializer end def pick_boot (vendor_rails? ? VendorBoot : GemBoot).new end def vendor_rails? File.exist?("#{RAILS_ROOT}/vendor/rails") end def preinitialize load(preinitializer_path) if File.exists?(preinitializer_path) end def preinitializer_path "#{RAILS_ROOT}/config/preinitializer.rb" end end class Boot def run load_initializer Rails::Initializer.run(:set_load_path) end end class VendorBoot < Boot def load_initializer require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer" end end class GemBoot < Boot def load_initializer self.class.load_rubygems load_rails_gem require 'initializer' end def load_rails_gem if version = self.class.gem_version gem 'rails', version else gem 'rails'

Page 45: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

156

end rescue Gem::LoadError => load_error $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.) exit 1 end class << self def rubygems_version Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion end def gem_version if defined? RAILS_GEM_VERSION RAILS_GEM_VERSION elsif ENV.include?('RAILS_GEM_VERSION') ENV['RAILS_GEM_VERSION'] else parse_gem_version(read_environment_rb) end end def load_rubygems require 'rubygems' unless rubygems_version >= '0.9.4' $stderr.puts %(Rails requires RubyGems >= 0.9.4 (you have #{rubygems_version}). Please `gem update --system` and try again.) exit 1 end rescue LoadError $stderr.puts %(Rails requires RubyGems >= 0.9.4. Please install RubyGems and try again: http://rubygems.rubyforge.org) exit 1 end def parse_gem_version(text) $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*'([!~<>=]*\s*[\d.]+)'/ end private def read_environment_rb File.read("#{RAILS_ROOT}/config/environment.rb") end end end end # All that for this: Rails.boot!

Page 46: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

157

Routes

ActionController::Routing::Routes.draw do |map| map.resources :destinos map.resources :votos map.resources :explicacions map.resources :admins map.resources :accounts #agencias map.root :controller => 'viajes' map.resources :viajes, :has_many => :ofertas , :has_many => :users map.namespace :admin do |admin| admin.resources :viajes end map.namespace :agencia do |agencia| agencia.resources :viajes, :has_many => :ofertas agencia.resources :ofertas, :belongs_to => :viaje, :belongs_to => :account, :has_many => :votos agencia.resources :accounts, :has_many => :ofertas end map.resources :users, :belongs_to => :viaje map.resource :session, :controller => 'session' map.signup '/signup', :controller => 'users', :action => 'new' map.login '/login', :controller => 'session', :action => 'new' map.logout '/logout', :controller => 'session', :action => 'destroy' end

Enviroments/development

# Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = false

Page 47: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

158

config.action_view.cache_template_extensions = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false

DB

Schema ActiveRecord::Schema.define(:version => 8) do create_table "accounts", :force => true do |t| t.string "login" t.string "password" t.datetime "created_at" t.datetime "updated_at" t.string "nombreagencia" t.string "emailagencia" t.string "nombreresponsable" t.string "ciudadagencia" t.integer "telefonoagencia" t.string "webagencia" t.string "avatar" t.string "nueva" t.string "conf_pass" end create_table "admins", :force => true do |t| t.string "login" t.string "password" t.datetime "created_at" t.datetime "updated_at" t.integer "telefono" end create_table "destinos", :force => true do |t| t.string "lugar" t.string "observaciones" t.datetime "created_at" t.datetime "updated_at" t.integer "user_id" t.integer "viaje_id" end create_table "entries", :force => true do |t| t.datetime "created_at" t.datetime "updated_at" end create_table "ofertas", :force => true do |t| t.integer "viaje_id" t.string "f_inicio" t.string "f_fin" t.string "origen" t.string "destino" t.integer "precio", :limit => 10, :precision => 10, :scale => 0 t.text "comentario" t.datetime "created_at"

Page 48: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

159

t.datetime "updated_at" t.string "loginagencia" t.integer "oferta_id" t.integer "account_id" t.integer "suma" end create_table "users", :force => true do |t| t.string "login" t.string "email" t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token" t.datetime "remember_token_expires_at" t.string "dni", :limit => 10 t.string "referencia" t.string "nombre" t.string "apellidos" t.integer "telefono", :limit => 10, :precision => 10, :scale => 0 t.string "avatar" t.integer "ok" t.string "edestino" t.integer "viaje_id" end create_table "viajes", :force => true do |t| t.string "nombre" t.string "origen" t.string "f_inicio" t.string "f_fin" t.string "f_v_d" t.string "f_v_v" t.string "adni" t.datetime "created_at" t.datetime "updated_at" t.string "universidad" t.string "estudios" t.integer "admin_id" end create_table "votos", :force => true do |t| t.integer "valor", :limit => 10, :precision => 10, :scale => 0 t.datetime "created_at" t.datetime "updated_at" t.integer "user_id" t.integer "oferta_id" t.integer "viaje_id" end end

Page 49: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

160

Migrate

Create_viajes class CreateViajes < ActiveRecord::Migration def self.up create_table :viajes do |t| t.string :nombre t.string :origen t.string :f_inicio t.string :f_fin t.string :f_v_d t.string :f_v_v t.string :adni t.references :admin t.timestamps end end def self.down drop_table :viajes end end

Create_ofertas class CreateOfertas < ActiveRecord::Migration def self.up create_table :ofertas do |t| t.references :viaje t.references :account t.string :f_inicio t.string :f_fin t.string :origen t.string :destino t.decimal :precio t.text :comentario t.string :loginagencia t.decimal :suma, :default => 0 t.timestamps end end def self.down drop_table :ofertas end end

Create_accounts class CreateAccounts < ActiveRecord::Migration def self.up create_table :accounts do |t| t.string :login t.string :password t.string :conf_pass t.string :nueva

Page 50: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

161

t.string :nombreagencia t.string :emailagencia t.string :nombreresponsable t.string :ciudadagencia t.decimal :telefonoagencia t.string :webagencia t.string :avatar t.timestamps end end def self.down drop_table :accounts end end

Create_admins class CreateAdmins < ActiveRecord::Migration def self.up create_table :admins do |t| t.string :login t.string :password t.decimal :telefono t.timestamps end end def self.down drop_table :admins end end

Create_users class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.references :viaje t.column :login, :string t.column :email, :string t.column :crypted_password, :string, :limit => 40 t.column :salt, :string, :limit => 40 t.column :created_at, :datetime t.column :updated_at, :datetime t.column :remember_token, :string t.column :remember_token_expires_at, :datetime t.column :dni, :string t.column :edestino, :string end end def self.down drop_table "users" end end

Page 51: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

162

Create_votos class CreateVotos < ActiveRecord::Migration def self.up create_table :votos do |t| t.references :user t.references :oferta t.references :viaje t.decimal :valor t.timestamps end end def self.down drop_table :votos end end

Create_destinos class CreateDestinos < ActiveRecord::Migration def self.up create_table :destinos do |t| t.references :user t.references :viaje t.string :lugar t.string :observaciones t.timestamps end end def self.down drop_table :destinos end end

LIB/Autheticated_system module AuthenticatedSystem protected # Returns true or false if the user is logged in. # Preloads @current_user with the user model if they're logged in. def logged_in? current_user != :false end # Accesses the current user from the session. Set it to :false if login fails # so that future calls do not hit the database. def current_user @current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie || :false) end

Page 52: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

163

# Store the given user id in the session. def current_user=(new_user) session[:user_id] = (new_user.nil? || new_user.is_a?(Symbol)) ? nil : new_user.id @current_user = new_user || :false end # Check if the user is authorized # # Override this method in your controllers if you want to restrict access # to only a few actions or if you want to check if the user # has the correct rights. # # Example: # # # only allow nonbobs # def authorized? # current_user.login != "bob" # end def authorized? logged_in? end # Filter method to enforce a login requirement. # # To require logins for all actions, use this in your controllers: # # before_filter :login_required # # To require logins for specific actions, use this in your controllers: # # before_filter :login_required, :only => [ :edit, :update ] # # To skip this in a subclassed controller: # # skip_before_filter :login_required # def login_required authorized? || access_denied end # Redirect as appropriate when an access request fails. # # The default action is to redirect to the login screen. # # Override this method in your controllers if you want to have special # behavior in case the user is not authorized # to access the requested action. For example, a popup window might # simply close itself. def access_denied respond_to do |format| format.html do store_location redirect_to new_session_path end format.any do request_http_basic_authentication 'Web Password'

Page 53: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

164

end end end # Store the URI of the current request in the session. # # We can return to this location by calling #redirect_back_or_default. def store_location session[:return_to] = request.request_uri end # Redirect to the URI stored by the most recent store_location call or # to the passed default. def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end # Inclusion hook to make #current_user and #logged_in? # available as ActionView helper methods. def self.included(base) base.send :helper_method, :current_user, :logged_in? end # Called from #current_user. First attempt to login by the user id stored in the session. def login_from_session self.current_user = User.find_by_id(session[:user_id]) if session[:user_id] end # Called from #current_user. Now, attempt to login by basic authentication information. def login_from_basic_auth authenticate_with_http_basic do |username, password| self.current_user = User.authenticate(username, password) end end # Called from #current_user. Finaly, attempt to login by an expiring token in the cookie. def login_from_cookie user = cookies[:auth_token] && User.find_by_remember_token(cookies[:auth_token]) if user && user.remember_token? user.remember_me cookies[:auth_token] = { :value => user.remember_token, :expires => user.remember_token_expires_at } self.current_user = user end end end

Page 54: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

165

PUBLIC/JAVASCRIPT

JS/ie-png var transparentImage = "images/none.gif"; function fixTrans() { if (typeof document.body.style.maxHeight == 'undefined') { var imgs = document.getElementsByTagName("img"); for (i = 0; i < imgs.length; i++) { if (imgs[i].src.indexOf(transparentImage) != -1) { return; } if (imgs[i].src.indexOf(".png") != -1) { var src = imgs[i].src; imgs[i].src = transparentImage; imgs[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')"; imgs[i].style.display = "inline-block"; } } } } if (document.all && !window.opera) attachEvent("onload", fixTrans);

Popup var popup; function initPopup () { popup = document.getElementById("popup"); document.getElementById("popup-display").onclick = function (){ popup.style.display = "block"; } document.getElementById("popup-close").onclick = function (){ popup.style.display = "none"; } } if (window.addEventListener) { window.addEventListener("load", initPopup, false); } else if (window.attachEvent) { window.attachEvent("onload", initPopup); }

Page 55: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

166

PUBLIC/STYLESHEETS All body { background: url(../images/body.gif) no-repeat 50% 0; background-color: #E0E0E0 ; font: 10px Verdana, 'Arial', Helvetica, sans-serif; margin: 0; } body.index { background: url(../images/body-index.gif) no-repeat 50% 0; background-color: #E0E0E0 ; } h1, h2, p, input, table, tr, td, ul { margin: 0; padding: 0; } ul {list-style: none;} form {display: inline;} #header { width: 1024px; height: 178px; margin: 0 auto; } div.popup { width: 50px; height: 219px; position: absolute; top: -220px; left: 580px; display: none; } div.popup div {background: url(../images/popup.png); width: 413px; height: 219px; } a.close { float: right; width: 19px; height: 19px; text-indent: -9999px; overflow: hidden; margin: 20px 22px 0 0; } div.popup span { display: block; text-indent: -9999px; overflow: hidden; } div.popup span.head-1 { background: url(../images/popup-span-1.png); width: 67px; height: 17px; display: inline; float: left; margin: 30px 0 0 30px; } div.popup span.head-2 { background: url(../images/popup-span-2.png) no-repeat 0 15px;

Page 56: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

167

width: 226px; height: 19px; clear: both; padding-top: 15px; margin: 0 0 0 30px; } input.string { background: url(../images/popup-input.gif) no-repeat; float: left; width: 124px; height: 15px; border: none; padding: 5px; margin: 25px 0 0 20px; } div.popup textarea { background: url(../images/textarea.gif); width: 326px; height: 46px; padding: 5px; margin: 15px 0 0 30px; position: relative; } input.popup-submit { float: right; margin: 10px 42px 0 0; } strong.logo { width: 529px; height: 90px; float: left; margin: 41px 0 0 283px; } strong.logo a { background: url(../images/logo.png) no-repeat; width: 529px; height: 90px; display: block; text-indent: -9999px; overflow: hidden; } div.entar { background: url(../images/entar.png); width: 204px; height: 167px; float: right; } div.entar span { background: url(../images/entar-span.png); width: 178px; height: 34px; display: block; text-indent: -9999px; overflow: hidden; margin: 35px 0 0 19px; } div.entar div { background: url(../images/entar-a.gif); width: 95px; height: 33px; padding: 2px 4px 4px 2px;

Page 57: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

168

margin: 12px 0 0 59px; } div.entar a { width: 95px; height: 33px; text-indent: -9999px; display: block; overflow: hidden; } div.avatar { background: url(../images/entar.png); width: 204px; height: 167px; float: right; overflow: hidden; } div.sub-avatar { width: 84px; float: left; } strong.avatar-top { background: url(../images/avatar-top-strong.gif); width: 84px; height: 15px; display: block; text-indent: -9999px; overflow: hidden; margin: 15px 0 0 20px; } span.avatar-top { width: 84px; height: 14px; display: block; text-indent: -9999px; overflow: hidden; margin: 15px 0 0 20px; } div.avatar img { float: right; margin-bottom: -30px; } strong.avatar-bottom { background: url(../images/avatar-bottom.gif) ; width: 188px; height: 22px; display: block; text-indent: -9999px; clear: both; overflow: hidden; margin: 14px 14px 14px 14px; } div.popup-display { background: url(../images/avatar-div.gif); width: 82px; height: 22px; float: right; padding: 2px 2px 4px 4px; margin: 1px 5px 0 0; } div.popup-display a {

Page 58: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

169

width: 82px; height: 22px; display: block; text-indent: -9999px; overflow: hidden; } a.desconectar { color: #102631; float: right; margin-top: -125px; } a.desconectar:hover {text-decoration: none;} #main { clear: both; width: 1024px; margin: 0 auto; } div.column { width: 206px; float: left; padding-top: 1px; } div.formbox { background: url(../images/formbox.png); width: 206px; height: 212px; overflow: hidden; } div.column label { display: block; text-indent: -9999px; clear: both; position: relative; } label.nombre { background: url(../images/nombre.gif); width: 81px; height: 24px; margin: 27px 0 2px 15px; } label.clave { background: url(../images/clave.gif); width: 60px; height: 26px; margin: 51px 0 0 14px; } * html label.clave { margin-top: 15px; } div.column span { background: url(../images/input.gif); width: 135px; height: 21px; float: left; padding: 5px 5px 1px; margin: 6px 0 0 13px; } div.column span input { background: none; border: none; width: 130px;

Page 59: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

170

height: 20px; position: relative; } input.submit { float: left; margin: 12px 0 0 5px; position: relative; } span.links { background: none !important; width: 206px !important; color: #102631; margin-top: 10px !important; } span.links a { color: #102631; text-decoration: none; position: relative; } span.links a:hover {text-decoration: underline;} div.column img { margin-left: 27px !important; } div.content { width: 677px; float: left; margin-left: 10px; } div.unete { background: url(../images/unete.png); width: 677px; height: 393px; overflow: hidden; } div.unete h1 { background: url(../images/unete-h1.png); width: 197px; height: 64px; text-indent: -9999px; overflow:hidden; margin: 60px 0 0 40px; } div.unete p { background: url(../images/unete-p.gif); width: 219px; height: 121px; text-indent: -9999px; overflow: hidden; margin: 49px 0 0 32px; } div.unete strong { background: url(../images/unete-strong.png); width: 317px; height: 41px; display: block; text-indent: -9999px; overflow: hidden; margin: 21px 0 0 37px; } div.part-1 { background: url(../images/part-1.png);

Page 60: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

171

width: 327px; height: 152px; float: left; margin-top: 13px; } div.part-1 a { background: url(../images/part-1-span.gif); width: 280px; height: 90px; display: block; text-indent: -9999px; overflow: hidden; margin: 29px 0 0 22px; } div.part-2 { background: url(../images/part-2.png); width: 327px; height: 152px; float: left; margin: 13px 0 0 23px; } div.part-2 a { background: url(../images/part-2-span.gif); width: 273px; height: 87px; display: block; text-indent: -9999px; overflow: hidden; margin: 30px 0 0 24px; } div.tablebox { background: url(../images/tablebox.png); width: 992px; height: 375px; padding: 14px 0 0 15px; margin-left: 10px; } tr.theader { background: none !important; height: 57px !important; } tr.theader td { text-indent: -9999px; overflow: hidden; } td.destino { background: url(../images/destino.gif) no-repeat; width: 159px; } td.precio { background: url(../images/precio.gif) no-repeat; width: 124px; } td.login { background: url(../images/login.gif) no-repeat; width: 112px; } td.caracteristicas { background: url(../images/caracteristicas.gif) no-repeat; width: 260px;

Page 61: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

172

} td.votos { background: url(../images/votos.gif) no-repeat; width: 168px; } td.dale { background: url(../images/dale.gif) no-repeat; width: 152px; } tr { height: 45px; } td { background: url(../images/table-row.gif) no-repeat 0 13px; font-size: 14px; text-align: center; height: 45px; } td.rounded { background-position: 100% 13px; } td.vota { background: none !important; } div.vota { background: url(../images/vota.png); float: left; width: 80px; height: 20px; display: inline; padding: 3px 3px 5px 5px; margin: 0 0 -4px 19px; } div.vota a { width: 80px; height: 20px; display: block; text-indent: -9999px; overflow: hidden; } td.nota { background: none; padding-left: 10px; } a.mas { background: url(../images/mas.gif) no-repeat; width: 93px; height: 23px; display: block; text-indent: -9999px; overflow: hidden; float: right; margin: 3px 25px 0 0; position: relative; } div.gallery { width: 1007px; padding-left: 10px; } div.gallery h2 { background: url(../images/inner-h2.png);

Page 62: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

173

width: 305px; height: 29px; text-indent: -9999px; overflow: hidden; margin-left: 367px; } div.sub-gallery { background: url(../images/gallery.png); width: 1007px; height: 151px; overflow: hidden; } div.add-gallery { background: url(../images/gallery-div.gif); width: 74px; height: 104px; float: left; text-indent: -9999px; overflow: hidden; margin: 22px 0 0 20px; } div.gallery ul { float: left; margin: 22px 0 0 0; position: relative; } div.gallery ul li { float: left; display: inline; margin-left: 14px; } div.gallery ul img { background: #fff; border: 1px solid #ebebeb; padding: 5px; } a.next { background: url(../images/next.gif); width: 30px; height: 56px; float: right; text-indent: -9999px; overflow: hidden; margin: 47px 25px 0 0px; position: relative; } div.footer { clear: both; text-align: center; padding-top: 5px; } div.registrate { clear: both; margin-right: 20px; text-align: right; padding-top: 0px; } div.nombre { font-size: 16px; clear: both;

Page 63: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

174

margin-top: -125px; margin-left: 20px; text-align: left; } div.soisya { font-size: 20px; clear: both; margin-top: 10px; margin-left: 15px; text-align: left; } div.enlace { font-size: 15px; margin-top: 10px; } div.referencia { font-size: 25px; margin-left: 200px; } div.tela { margin-right: 10px; text-align: right; font-size: 15px; margin-top: 0px; } div.lalala{background: url(../images/lalala.gif); width: 243px; height: 258px; float: left; text-indent: -9999px; overflow: hidden; margin: -300px 0 0 700px; } div.lalala2{background: url(../images/lalala2.png); width: 243px; height: 258px; float: left; text-indent: -9999px; overflow: hidden; margin: -300px 0 0 700px; } div.destino { color: #000099; font-size: 16px; clear: both; margin-top: 20px; text-align: center;} div.destino2 { color: #000000; font-size: 18px; clear: both; margin-top: 20px; text-align: center;

Page 64: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

175

Ie #header strong a { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/logo.png', sizingmethod='crop'); cursor: pointer; } div.entar { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/entar.png', sizingmethod='crop'); } div.entar span { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/entar-span.png', sizingmethod='crop'); } div.formbox { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/formbox.png', sizingmethod='crop'); } div.column img { width: 131px; height: 101px; } div.unete { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/unete.png', sizingmethod='crop'); } div.unete h1 { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/unete-h1.png', sizingmethod='crop'); } div.unete strong { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/unete-strong.png', sizingmethod='crop'); } div.part-1 { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/part-1.png', sizingmethod='crop'); } div.part-2 { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/part-2.png', sizingmethod='crop'); } div.avatar { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/entar.png', sizingmethod='crop'); } div.tablebox { background:none fixed;

Page 65: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

176

filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/tablebox.png', sizingmethod='crop'); } div.vota a {positioN: relative;} div.vota { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/vota.png', sizingmethod='crop'); } div.gallery h2 { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/inner-h2.png', sizingmethod='crop'); } div.sub-gallery { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/gallery.png', sizingmethod='crop'); } div.popup div { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/popup.png', sizingmethod='crop'); } div.popup span.head-1 { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/popup-span-1.png', sizingmethod='crop'); } div.popup span.head-2 { background:none fixed; filter:progid:dximagetransform.microsoft.alphaimageloader(src='images/popup-span-2.png', sizingmethod='crop'); padding-top: 0; margin-top: 15px; } div.entar a, div.avatar a, div.popup input, div.popup a, div.popup label { position: relative; }

Scaffold body { background-color: #66ff66; color: #333; font-family: 'Comic Sans MS',verdana,arial,helvetica,sans-serif; font-size: 10px; } body, p, ol, ul, td { font-family: Comic Sans MS,verdana,arial,'helvetica',sans-serif; font-size: 12px; line-height: 20px; background-color: #ccff99; }

Page 66: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

177

pre { background-color: #eee; padding: 10px; font-size: 11px; } a { color: #111; } a:visited { color: #555; } a:hover { color: #fff; background-color:#000; } .fieldWithErrors { padding: 2px; background-color: red; display: table; } #errorExplanation { width: 400px; border: 2px solid red; padding: 7px; padding-bottom: 12px; margin-bottom: 20px; background-color: #f0f0f0; } #errorExplanation h2 { text-align: left; font-weight: bold; padding: 5px 5px 5px 15px; font-size: 12px; margin: -7px; background-color: #c00; color: #fff; } #errorExplanation p { color: #333; margin-bottom: 0; padding: 5px; } #errorExplanation ul li { font-size: 12px; list-style: square; } div.uploadStatus { margin: 5px; } div.progressBar { margin: 5px; } div.progressBar div.border { background-color: #fff; border: 1px solid grey; width: 100%; } div.progressBar div.background {

Page 67: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

178

background-color: #333; height: 18px; width: 0%; }

PLUGINS Esta carpeta contiene los archivos de todos los plugins decargados de los

repositorios. No los incluyo en este documento, ya que lo considero algo

innecesario.

ALGUNO DE LOS ARCHIVOS INCLUIDOS POR DEFECTO (no

es necesario modificar ninguno, salvo características

especiales)

Public/Javascripts/Effects String.prototype.parseColor = function() { var color = '#'; if (this.slice(0,4) == 'rgb(') { var cols = this.slice(4,this.length-1).split(','); var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); } else { if (this.slice(0,1) == '#') { if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); if (this.length==7) color = this.toLowerCase(); } } return (color.length==7 ? color : (arguments[0] || this)); }; /*--------------------------------------------------------------------------*/ Element.collectTextNodes = function(element) { return $A($(element).childNodes).collect( function(node) { return (node.nodeType==3 ? node.nodeValue : (node.hasChildNodes() ? Element.collectTextNodes(node) : '')); }).flatten().join(''); }; Element.collectTextNodesIgnoreClass = function(element, className) { return $A($(element).childNodes).collect( function(node) { return (node.nodeType==3 ? node.nodeValue : ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? Element.collectTextNodesIgnoreClass(node, className) : '')); }).flatten().join(''); };

Page 68: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

179

Element.setContentZoom = function(element, percent) { element = $(element); element.setStyle({fontSize: (percent/100) + 'em'}); if (Prototype.Browser.WebKit) window.scrollBy(0,0); return element; }; Element.getInlineOpacity = function(element){ return $(element).style.opacity || ''; }; Element.forceRerendering = function(element) { try { element = $(element); var n = document.createTextNode(' '); element.appendChild(n); element.removeChild(n); } catch(e) { } }; /*--------------------------------------------------------------------------*/ var Effect = { _elementDoesNotExistError: { name: 'ElementDoesNotExistError', message: 'The specified DOM element does not exist, but is required for this effect to operate' }, Transitions: { linear: Prototype.K, sinoidal: function(pos) { return (-Math.cos(pos*Math.PI)/2) + 0.5; }, reverse: function(pos) { return 1-pos; }, flicker: function(pos) { var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4; return pos > 1 ? 1 : pos; }, wobble: function(pos) { return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5; }, pulse: function(pos, pulses) { pulses = pulses || 5; return ( ((pos % (1/pulses)) * pulses).round() == 0 ? ((pos * pulses * 2) - (pos * pulses * 2).floor()) : 1 - ((pos * pulses * 2) - (pos * pulses * 2).floor()) ); }, spring: function(pos) { return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); }, none: function(pos) { return 0; }, full: function(pos) { return 1;

Page 69: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

180

} }, DefaultOptions: { duration: 1.0, // seconds fps: 100, // 100= assume 66fps max. sync: false, // true for combining from: 0.0, to: 1.0, delay: 0.0, queue: 'parallel' }, tagifyText: function(element) { var tagifyStyle = 'position:relative'; if (Prototype.Browser.IE) tagifyStyle += ';zoom:1'; element = $(element); $A(element.childNodes).each( function(child) { if (child.nodeType==3) { child.nodeValue.toArray().each( function(character) { element.insertBefore( new Element('span', {style: tagifyStyle}).update( character == ' ' ? String.fromCharCode(160) : character), child); }); Element.remove(child); } }); }, multiple: function(element, effect) { var elements; if (((typeof element == 'object') || Object.isFunction(element)) && (element.length)) elements = element; else elements = $(element).childNodes; var options = Object.extend({ speed: 0.1, delay: 0.0 }, arguments[2] || { }); var masterDelay = options.delay; $A(elements).each( function(element, index) { new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay })); }); }, PAIRS: { 'slide': ['SlideDown','SlideUp'], 'blind': ['BlindDown','BlindUp'], 'appear': ['Appear','Fade'] }, toggle: function(element, effect) { element = $(element); effect = (effect || 'appear').toLowerCase(); var options = Object.extend({ queue: { position:'end', scope:(element.id || 'global'), limit: 1 } }, arguments[2] || { });

Page 70: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

181

Effect[element.visible() ? Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options); } }; Effect.DefaultOptions.transition = Effect.Transitions.sinoidal; /* ------------- core effects ------------- */ Effect.ScopedQueue = Class.create(Enumerable, { initialize: function() { this.effects = []; this.interval = null; }, _each: function(iterator) { this.effects._each(iterator); }, add: function(effect) { var timestamp = new Date().getTime(); var position = Object.isString(effect.options.queue) ? effect.options.queue : effect.options.queue.position; switch(position) { case 'front': // move unstarted effects after this effect this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) { e.startOn += effect.finishOn; e.finishOn += effect.finishOn; }); break; case 'with-last': timestamp = this.effects.pluck('startOn').max() || timestamp; break; case 'end': // start effect after last queued effect has finished timestamp = this.effects.pluck('finishOn').max() || timestamp; break; } effect.startOn += timestamp; effect.finishOn += timestamp; if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) this.effects.push(effect); if (!this.interval) this.interval = setInterval(this.loop.bind(this), 15); }, remove: function(effect) { this.effects = this.effects.reject(function(e) { return e==effect }); if (this.effects.length == 0) { clearInterval(this.interval); this.interval = null; } }, loop: function() {

Page 71: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

182

var timePos = new Date().getTime(); for(var i=0, len=this.effects.length;i<len;i++) this.effects[i] && this.effects[i].loop(timePos); } }); Effect.Queues = { instances: $H(), get: function(queueName) { if (!Object.isString(queueName)) return queueName; return this.instances.get(queueName) || this.instances.set(queueName, new Effect.ScopedQueue()); } }; Effect.Queue = Effect.Queues.get('global'); Effect.Base = Class.create({ position: null, start: function(options) { function codeForEvent(options,eventName){ return ( (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') + (options[eventName] ? 'this.options.'+eventName+'(this);' : '') ); } if (options && options.transition === false) options.transition = Effect.Transitions.linear; this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { }); this.currentFrame = 0; this.state = 'idle'; this.startOn = this.options.delay*1000; this.finishOn = this.startOn+(this.options.duration*1000); this.fromToDelta = this.options.to-this.options.from; this.totalTime = this.finishOn-this.startOn; this.totalFrames = this.options.fps*this.options.duration; eval('this.render = function(pos){ '+ 'if (this.state=="idle"){this.state="running";'+ codeForEvent(this.options,'beforeSetup')+ (this.setup ? 'this.setup();':'')+ codeForEvent(this.options,'afterSetup')+ '};if (this.state=="running"){'+ 'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+ 'this.position=pos;'+ codeForEvent(this.options,'beforeUpdate')+ (this.update ? 'this.update(pos);':'')+ codeForEvent(this.options,'afterUpdate')+ '}}'); this.event('beforeStart'); if (!this.options.sync) Effect.Queues.get(Object.isString(this.options.queue) ? 'global' : this.options.queue.scope).add(this); }, loop: function(timePos) {

Page 72: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

183

if (timePos >= this.startOn) { if (timePos >= this.finishOn) { this.render(1.0); this.cancel(); this.event('beforeFinish'); if (this.finish) this.finish(); this.event('afterFinish'); return; } var pos = (timePos - this.startOn) / this.totalTime, frame = (pos * this.totalFrames).round(); if (frame > this.currentFrame) { this.render(pos); this.currentFrame = frame; } } }, cancel: function() { if (!this.options.sync) Effect.Queues.get(Object.isString(this.options.queue) ? 'global' : this.options.queue.scope).remove(this); this.state = 'finished'; }, event: function(eventName) { if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this); if (this.options[eventName]) this.options[eventName](this); }, inspect: function() { var data = $H(); for(property in this) if (!Object.isFunction(this[property])) data.set(property, this[property]); return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>'; } }); Effect.Parallel = Class.create(Effect.Base, { initialize: function(effects) { this.effects = effects || []; this.start(arguments[1]); }, update: function(position) { this.effects.invoke('render', position); }, finish: function(position) { this.effects.each( function(effect) { effect.render(1.0); effect.cancel(); effect.event('beforeFinish'); if (effect.finish) effect.finish(position); effect.event('afterFinish'); }); } }); Effect.Tween = Class.create(Effect.Base, { initialize: function(object, from, to) { object = Object.isString(object) ? $(object) : object; var args = $A(arguments), method = args.last(),

Page 73: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

184

options = args.length == 5 ? args[3] : null; this.method = Object.isFunction(method) ? method.bind(object) : Object.isFunction(object[method]) ? object[method].bind(object) : function(value) { object[method] = value }; this.start(Object.extend({ from: from, to: to }, options || { })); }, update: function(position) { this.method(position); } }); Effect.Event = Class.create(Effect.Base, { initialize: function() { this.start(Object.extend({ duration: 0 }, arguments[0] || { })); }, update: Prototype.emptyFunction }); Effect.Opacity = Class.create(Effect.Base, { initialize: function(element) { this.element = $(element); if (!this.element) throw(Effect._elementDoesNotExistError); // make this work on IE on elements without 'layout' if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) this.element.setStyle({zoom: 1}); var options = Object.extend({ from: this.element.getOpacity() || 0.0, to: 1.0 }, arguments[1] || { }); this.start(options); }, update: function(position) { this.element.setOpacity(position); } }); Effect.Move = Class.create(Effect.Base, { initialize: function(element) { this.element = $(element); if (!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ x: 0, y: 0, mode: 'relative' }, arguments[1] || { }); this.start(options); }, setup: function() { this.element.makePositioned(); this.originalLeft = parseFloat(this.element.getStyle('left') || '0'); this.originalTop = parseFloat(this.element.getStyle('top') || '0'); if (this.options.mode == 'absolute') { this.options.x = this.options.x - this.originalLeft; this.options.y = this.options.y - this.originalTop; } }, update: function(position) {

Page 74: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

185

this.element.setStyle({ left: (this.options.x * position + this.originalLeft).round() + 'px', top: (this.options.y * position + this.originalTop).round() + 'px' }); } }); // for backwards compatibility Effect.MoveBy = function(element, toTop, toLeft) { return new Effect.Move(element, Object.extend({ x: toLeft, y: toTop }, arguments[3] || { })); }; Effect.Scale = Class.create(Effect.Base, { initialize: function(element, percent) { this.element = $(element); if (!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ scaleX: true, scaleY: true, scaleContent: true, scaleFromCenter: false, scaleMode: 'box', // 'box' or 'contents' or { } with provided values scaleFrom: 100.0, scaleTo: percent }, arguments[2] || { }); this.start(options); }, setup: function() { this.restoreAfterFinish = this.options.restoreAfterFinish || false; this.elementPositioning = this.element.getStyle('position'); this.originalStyle = { }; ['top','left','width','height','fontSize'].each( function(k) { this.originalStyle[k] = this.element.style[k]; }.bind(this)); this.originalTop = this.element.offsetTop; this.originalLeft = this.element.offsetLeft; var fontSize = this.element.getStyle('font-size') || '100%'; ['em','px','%','pt'].each( function(fontSizeType) { if (fontSize.indexOf(fontSizeType)>0) { this.fontSize = parseFloat(fontSize); this.fontSizeType = fontSizeType; } }.bind(this)); this.factor = (this.options.scaleTo - this.options.scaleFrom)/100; this.dims = null; if (this.options.scaleMode=='box') this.dims = [this.element.offsetHeight, this.element.offsetWidth]; if (/^content/.test(this.options.scaleMode)) this.dims = [this.element.scrollHeight, this.element.scrollWidth];

Page 75: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

186

if (!this.dims) this.dims = [this.options.scaleMode.originalHeight, this.options.scaleMode.originalWidth]; }, update: function(position) { var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); if (this.options.scaleContent && this.fontSize) this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType }); this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale); }, finish: function(position) { if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle); }, setDimensions: function(height, width) { var d = { }; if (this.options.scaleX) d.width = width.round() + 'px'; if (this.options.scaleY) d.height = height.round() + 'px'; if (this.options.scaleFromCenter) { var topd = (height - this.dims[0])/2; var leftd = (width - this.dims[1])/2; if (this.elementPositioning == 'absolute') { if (this.options.scaleY) d.top = this.originalTop-topd + 'px'; if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; } else { if (this.options.scaleY) d.top = -topd + 'px'; if (this.options.scaleX) d.left = -leftd + 'px'; } } this.element.setStyle(d); } }); Effect.Highlight = Class.create(Effect.Base, { initialize: function(element) { this.element = $(element); if (!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { }); this.start(options); }, setup: function() { // Prevent executing on elements not in the layout flow if (this.element.getStyle('display')=='none') { this.cancel(); return; } // Disable background image during the effect this.oldStyle = { }; if (!this.options.keepBackgroundImage) { this.oldStyle.backgroundImage = this.element.getStyle('background-image'); this.element.setStyle({backgroundImage: 'none'}); } if (!this.options.endcolor) this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff'); if (!this.options.restorecolor)

Page 76: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

187

this.options.restorecolor = this.element.getStyle('background-color'); // init color calculations this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this)); this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this)); }, update: function(position) { this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){ return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) }); }, finish: function() { this.element.setStyle(Object.extend(this.oldStyle, { backgroundColor: this.options.restorecolor })); } }); Effect.ScrollTo = function(element) { var options = arguments[1] || { }, scrollOffsets = document.viewport.getScrollOffsets(), elementOffsets = $(element).cumulativeOffset(), max = (window.height || document.body.scrollHeight) - document.viewport.getHeight(); if (options.offset) elementOffsets[1] += options.offset; return new Effect.Tween(null, scrollOffsets.top, elementOffsets[1] > max ? max : elementOffsets[1], options, function(p){ scrollTo(scrollOffsets.left, p.round()) } ); }; /* ------------- combination effects ------------- */ Effect.Fade = function(element) { element = $(element); var oldOpacity = element.getInlineOpacity(); var options = Object.extend({ from: element.getOpacity() || 1.0, to: 0.0, afterFinishInternal: function(effect) { if (effect.options.to!=0) return; effect.element.hide().setStyle({opacity: oldOpacity}); } }, arguments[1] || { }); return new Effect.Opacity(element,options); }; Effect.Appear = function(element) { element = $(element); var options = Object.extend({ from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),

Page 77: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

188

to: 1.0, // force Safari to render floated elements properly afterFinishInternal: function(effect) { effect.element.forceRerendering(); }, beforeSetup: function(effect) { effect.element.setOpacity(effect.options.from).show(); }}, arguments[1] || { }); return new Effect.Opacity(element,options); }; Effect.Puff = function(element) { element = $(element); var oldStyle = { opacity: element.getInlineOpacity(), position: element.getStyle('position'), top: element.style.top, left: element.style.left, width: element.style.width, height: element.style.height }; return new Effect.Parallel( [ new Effect.Scale(element, 200, { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], Object.extend({ duration: 1.0, beforeSetupInternal: function(effect) { Position.absolutize(effect.effects[0].element) }, afterFinishInternal: function(effect) { effect.effects[0].element.hide().setStyle(oldStyle); } }, arguments[1] || { }) ); }; Effect.BlindUp = function(element) { element = $(element); element.makeClipping(); return new Effect.Scale(element, 0, Object.extend({ scaleContent: false, scaleX: false, restoreAfterFinish: true, afterFinishInternal: function(effect) { effect.element.hide().undoClipping(); } }, arguments[1] || { }) ); }; Effect.BlindDown = function(element) { element = $(element); var elementDimensions = element.getDimensions(); return new Effect.Scale(element, 100, Object.extend({ scaleContent: false, scaleX: false, scaleFrom: 0, scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, restoreAfterFinish: true, afterSetup: function(effect) {

Page 78: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

189

effect.element.makeClipping().setStyle({height: '0px'}).show(); }, afterFinishInternal: function(effect) { effect.element.undoClipping(); } }, arguments[1] || { })); }; Effect.SwitchOff = function(element) { element = $(element); var oldOpacity = element.getInlineOpacity(); return new Effect.Appear(element, Object.extend({ duration: 0.4, from: 0, transition: Effect.Transitions.flicker, afterFinishInternal: function(effect) { new Effect.Scale(effect.element, 1, { duration: 0.3, scaleFromCenter: true, scaleX: false, scaleContent: false, restoreAfterFinish: true, beforeSetup: function(effect) { effect.element.makePositioned().makeClipping(); }, afterFinishInternal: function(effect) { effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity}); } }) } }, arguments[1] || { })); }; Effect.DropOut = function(element) { element = $(element); var oldStyle = { top: element.getStyle('top'), left: element.getStyle('left'), opacity: element.getInlineOpacity() }; return new Effect.Parallel( [ new Effect.Move(element, {x: 0, y: 100, sync: true }), new Effect.Opacity(element, { sync: true, to: 0.0 }) ], Object.extend( { duration: 0.5, beforeSetup: function(effect) { effect.effects[0].element.makePositioned(); }, afterFinishInternal: function(effect) { effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle); } }, arguments[1] || { })); }; Effect.Shake = function(element) { element = $(element); var options = Object.extend({ distance: 20, duration: 0.5 }, arguments[1] || {}); var distance = parseFloat(options.distance); var split = parseFloat(options.duration) / 10.0;

Page 79: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

190

var oldStyle = { top: element.getStyle('top'), left: element.getStyle('left') }; return new Effect.Move(element, { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) { effect.element.undoPositioned().setStyle(oldStyle); }}) }}) }}) }}) }}) }}); }; Effect.SlideDown = function(element) { element = $(element).cleanWhitespace(); // SlideDown need to have the content of the element wrapped in a container element with fixed height! var oldInnerBottom = element.down().getStyle('bottom'); var elementDimensions = element.getDimensions(); return new Effect.Scale(element, 100, Object.extend({ scaleContent: false, scaleX: false, scaleFrom: window.opera ? 0 : 1, scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, restoreAfterFinish: true, afterSetup: function(effect) { effect.element.makePositioned(); effect.element.down().makePositioned(); if (window.opera) effect.element.setStyle({top: ''}); effect.element.makeClipping().setStyle({height: '0px'}).show(); }, afterUpdateInternal: function(effect) { effect.element.down().setStyle({bottom: (effect.dims[0] - effect.element.clientHeight) + 'px' }); }, afterFinishInternal: function(effect) { effect.element.undoClipping().undoPositioned(); effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); } }, arguments[1] || { }) ); }; Effect.SlideUp = function(element) { element = $(element).cleanWhitespace(); var oldInnerBottom = element.down().getStyle('bottom'); var elementDimensions = element.getDimensions(); return new Effect.Scale(element, window.opera ? 0 : 1,

Page 80: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

191

Object.extend({ scaleContent: false, scaleX: false, scaleMode: 'box', scaleFrom: 100, scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, restoreAfterFinish: true, afterSetup: function(effect) { effect.element.makePositioned(); effect.element.down().makePositioned(); if (window.opera) effect.element.setStyle({top: ''}); effect.element.makeClipping().show(); }, afterUpdateInternal: function(effect) { effect.element.down().setStyle({bottom: (effect.dims[0] - effect.element.clientHeight) + 'px' }); }, afterFinishInternal: function(effect) { effect.element.hide().undoClipping().undoPositioned(); effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); } }, arguments[1] || { }) ); }; // Bug in opera makes the TD containing this element expand for a instance after finish Effect.Squish = function(element) { return new Effect.Scale(element, window.opera ? 1 : 0, { restoreAfterFinish: true, beforeSetup: function(effect) { effect.element.makeClipping(); }, afterFinishInternal: function(effect) { effect.element.hide().undoClipping(); } }); }; Effect.Grow = function(element) { element = $(element); var options = Object.extend({ direction: 'center', moveTransition: Effect.Transitions.sinoidal, scaleTransition: Effect.Transitions.sinoidal, opacityTransition: Effect.Transitions.full }, arguments[1] || { }); var oldStyle = { top: element.style.top, left: element.style.left, height: element.style.height, width: element.style.width, opacity: element.getInlineOpacity() }; var dims = element.getDimensions(); var initialMoveX, initialMoveY; var moveX, moveY; switch (options.direction) { case 'top-left':

Page 81: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

192

initialMoveX = initialMoveY = moveX = moveY = 0; break; case 'top-right': initialMoveX = dims.width; initialMoveY = moveY = 0; moveX = -dims.width; break; case 'bottom-left': initialMoveX = moveX = 0; initialMoveY = dims.height; moveY = -dims.height; break; case 'bottom-right': initialMoveX = dims.width; initialMoveY = dims.height; moveX = -dims.width; moveY = -dims.height; break; case 'center': initialMoveX = dims.width / 2; initialMoveY = dims.height / 2; moveX = -dims.width / 2; moveY = -dims.height / 2; break; } return new Effect.Move(element, { x: initialMoveX, y: initialMoveY, duration: 0.01, beforeSetup: function(effect) { effect.element.hide().makeClipping().makePositioned(); }, afterFinishInternal: function(effect) { new Effect.Parallel( [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }), new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }), new Effect.Scale(effect.element, 100, { scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true}) ], Object.extend({ beforeSetup: function(effect) { effect.effects[0].element.setStyle({height: '0px'}).show(); }, afterFinishInternal: function(effect) { effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); } }, options) ) } }); }; Effect.Shrink = function(element) {

Page 82: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

193

element = $(element); var options = Object.extend({ direction: 'center', moveTransition: Effect.Transitions.sinoidal, scaleTransition: Effect.Transitions.sinoidal, opacityTransition: Effect.Transitions.none }, arguments[1] || { }); var oldStyle = { top: element.style.top, left: element.style.left, height: element.style.height, width: element.style.width, opacity: element.getInlineOpacity() }; var dims = element.getDimensions(); var moveX, moveY; switch (options.direction) { case 'top-left': moveX = moveY = 0; break; case 'top-right': moveX = dims.width; moveY = 0; break; case 'bottom-left': moveX = 0; moveY = dims.height; break; case 'bottom-right': moveX = dims.width; moveY = dims.height; break; case 'center': moveX = dims.width / 2; moveY = dims.height / 2; break; } return new Effect.Parallel( [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }), new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}), new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }) ], Object.extend({ beforeStartInternal: function(effect) { effect.effects[0].element.makePositioned().makeClipping(); }, afterFinishInternal: function(effect) { effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); } }, options) ); }; Effect.Pulsate = function(element) { element = $(element); var options = arguments[1] || { };

Page 83: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

194

var oldOpacity = element.getInlineOpacity(); var transition = options.transition || Effect.Transitions.sinoidal; var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) }; reverser.bind(transition); return new Effect.Opacity(element, Object.extend(Object.extend({ duration: 2.0, from: 0, afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); } }, options), {transition: reverser})); }; Effect.Fold = function(element) { element = $(element); var oldStyle = { top: element.style.top, left: element.style.left, width: element.style.width, height: element.style.height }; element.makeClipping(); return new Effect.Scale(element, 5, Object.extend({ scaleContent: false, scaleX: false, afterFinishInternal: function(effect) { new Effect.Scale(element, 1, { scaleContent: false, scaleY: false, afterFinishInternal: function(effect) { effect.element.hide().undoClipping().setStyle(oldStyle); } }); }}, arguments[1] || { })); }; Effect.Morph = Class.create(Effect.Base, { initialize: function(element) { this.element = $(element); if (!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ style: { } }, arguments[1] || { }); if (!Object.isString(options.style)) this.style = $H(options.style); else { if (options.style.include(':')) this.style = options.style.parseStyle(); else { this.element.addClassName(options.style); this.style = $H(this.element.getStyles()); this.element.removeClassName(options.style); var css = this.element.getStyles(); this.style = this.style.reject(function(style) { return style.value == css[style.key]; }); options.afterFinishInternal = function(effect) { effect.element.addClassName(effect.options.style); effect.transforms.each(function(transform) { effect.element.style[transform.style] = ''; }); } }

Page 84: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

195

} this.start(options); }, setup: function(){ function parseColor(color){ if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff'; color = color.parseColor(); return $R(0,2).map(function(i){ return parseInt( color.slice(i*2+1,i*2+3), 16 ) }); } this.transforms = this.style.map(function(pair){ var property = pair[0], value = pair[1], unit = null; if (value.parseColor('#zzzzzz') != '#zzzzzz') { value = value.parseColor(); unit = 'color'; } else if (property == 'opacity') { value = parseFloat(value); if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) this.element.setStyle({zoom: 1}); } else if (Element.CSS_LENGTH.test(value)) { var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/); value = parseFloat(components[1]); unit = (components.length == 3) ? components[2] : null; } var originalValue = this.element.getStyle(property); return { style: property.camelize(), originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), targetValue: unit=='color' ? parseColor(value) : value, unit: unit }; }.bind(this)).reject(function(transform){ return ( (transform.originalValue == transform.targetValue) || ( transform.unit != 'color' && (isNaN(transform.originalValue) || isNaN(transform.targetValue)) ) ) }); }, update: function(position) { var style = { }, transform, i = this.transforms.length; while(i--) style[(transform = this.transforms[i]).style] = transform.unit=='color' ? '#'+ (Math.round(transform.originalValue[0]+ (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() + (Math.round(transform.originalValue[1]+ (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() + (Math.round(transform.originalValue[2]+

Page 85: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

196

(transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() : (transform.originalValue + (transform.targetValue - transform.originalValue) * position).toFixed(3) + (transform.unit === null ? '' : transform.unit); this.element.setStyle(style, true); } }); Effect.Transform = Class.create({ initialize: function(tracks){ this.tracks = []; this.options = arguments[1] || { }; this.addTracks(tracks); }, addTracks: function(tracks){ tracks.each(function(track){ track = $H(track); var data = track.values().first(); this.tracks.push($H({ ids: track.keys().first(), effect: Effect.Morph, options: { style: data } })); }.bind(this)); return this; }, play: function(){ return new Effect.Parallel( this.tracks.map(function(track){ var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options'); var elements = [$(ids) || $$(ids)].flatten(); return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) }); }).flatten(), this.options ); } }); Element.CSS_PROPERTIES = $w( 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' + 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' + 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' + 'fontSize fontWeight height left letterSpacing lineHeight ' + 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+ 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' + 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' + 'right textIndent top width wordSpacing zIndex'); Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/; String.__parseStyleElement = document.createElement('div');

Page 86: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

197

String.prototype.parseStyle = function(){ var style, styleRules = $H(); if (Prototype.Browser.WebKit) style = new Element('div',{style:this}).style; else { String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>'; style = String.__parseStyleElement.childNodes[0].style; } Element.CSS_PROPERTIES.each(function(property){ if (style[property]) styleRules.set(property, style[property]); }); if (Prototype.Browser.IE && this.include('opacity')) styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]); return styleRules; }; if (document.defaultView && document.defaultView.getComputedStyle) { Element.getStyles = function(element) { var css = document.defaultView.getComputedStyle($(element), null); return Element.CSS_PROPERTIES.inject({ }, function(styles, property) { styles[property] = css[property]; return styles; }); }; } else { Element.getStyles = function(element) { element = $(element); var css = element.currentStyle, styles; styles = Element.CSS_PROPERTIES.inject({ }, function(hash, property) { hash.set(property, css[property]); return hash; }); if (!styles.opacity) styles.set('opacity', element.getOpacity()); return styles; }; }; Effect.Methods = { morph: function(element, style) { element = $(element); new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { })); return element; }, visualEffect: function(element, effect, options) { element = $(element) var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1); new Effect[klass](element, options); return element; }, highlight: function(element, options) { element = $(element); new Effect.Highlight(element, options);

Page 87: 9. C.digo fuente - bibing.us.esbibing.us.es/proyectos/abreproy/11707/descargar_fichero/proyecto...find_by_login_and_password(l, Digest::SHA1.hexdigest(p)) end has_many :ofertas ...

Quenospiramos Juan Miguel Dicenta Garcia

198

return element; } }; $w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+ 'pulsate shake puff squish switchOff dropOut').each( function(effect) { Effect.Methods[effect] = function(element, options){ element = $(element); Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options); return element; } } ); $w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( function(f) { Effect.Methods[f] = Element[f]; } ); Element.addMethods(Effect.Methods);