CentOS install nginx

March 20th, 2014 No comments

nginx-logoHow to install nginx on CentOS?

When you try install by command:

 Bash |  copy code |? 
1
sudo yum install nginx

you will get “No package nginx available”.

You need to add EPEL repository by:

 Bash |  copy code |? 
1
sudo rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm

And try to run:

 Bash |  copy code |? 
1
sudo yum install nginx

If you still having some troubles try:

 Bash |  copy code |? 
1
sudo yum clean all

Podziel się!
Categories: Linux, Web Tags: , ,

Mongoid embeds_many and views

March 11th, 2014 No comments

How to make views to add/remove embedded objects in Mongoid?

Background

Mongoid has nice feature of embeding one document in another. In my example I want to keep email addresses and phone numbers in person object instead of relations.

Using:

Coocon gem to make things easier in views

Formtastic gem for forms

HAML for views

Mongoid as database backend

Bootstrap for CSS layouts

Models

Contact person. In this case we want the whole thing, like models, controllers and views…

 Bash |  copy code |? 
1
rails generate scaffold ContactPerson person_title:string person_give_name:string person_middle_name:string string person_family_name:string

Email

 Bash |  copy code |? 
1
rails generate model email email:string

Phone

 Bash |  copy code |? 
1
rails generate model country_code:string number:string extension:string

Setting embedding in models

ContactPerson

Thanks to “accepts_nested_attributes_for” we can get into emails and phone numbers through the contact person object. http://api.rubyonrails.org/v4.0.1/classes/ActiveRecord/NestedAttributes/ClassMethods.html

 Rails |  copy code |? 
01
class ContactPerson
02
  include Mongoid::Document
03
  embeds_many :email
04
  embeds_many :phone
05
 
06
  accepts_nested_attributes_for :email, reject_if: :all_blank, allow_destroy: true
07
  accepts_nested_attributes_for :phone, reject_if: :all_blank, allow_destroy: true
08
 
09
  field :person_title, type: String
10
  field :person_give_name, type: String
11
  field :person_middle_name, type: String
12
  field :person_family_name, type: String
13
 
14
end

Phone

Here we have only “embedded_in” to tell that this is embedded in another document.

 Rails |  copy code |? 
1
class Phone
2
  include Mongoid::Document
3
 
4
  embedded_in :contact_person
5
 
6
  field :country_code, type: String
7
  field :number, type: String
8
  field :extension, type: String
9
end

Email

Same thing

 Rails |  copy code |? 
1
class Email
2
  include Mongoid::Document
3
  field :email, type: String
4
  embedded_in :contact_person
5
end
6

Views

So now we should have working scaffolds to add/edit/remove ContactPersons. But… we need to add/remove phone numbers and emails.

contact_person

Lets start from organising space by Bootstraps grid layout and setting more proper labels above textfields.

So in app/views/contact_people/_form.html.haml instead of:

 Rails |  copy code |? 
1
= f.input :person_title
2
= f.input :person_give_name
3
= f.input :person_middle_name
4
= f.input :person_family_name

We will have:

 Rails |  copy code |? 
01
      .col-md-1
02
        = label_tag "Title"
03
        = f.input :person_title, label: false
04
      .col-md-4
05
        = label_tag "Name"
06
        = f.input :person_give_name, label: false
07
      .col-md-3
08
        = label_tag "Middle name"
09
        = f.input :person_middle_name, label: false
10
      .col-md-4
11
        = label_tag "Surname"
12
        = f.input :person_family_name, label: false

Start dealing with embedded elements – partial for email form

Create file: app/views/contact_people/_email_fields.html.haml

At start we have div “.panel-body” because our emails will be boxed in nice looking bootstrap panel. Then there is a formtastic loop to generate form. In the end we have link to delete email address. As bonus you have remove icon from bootstrap and bootstrap button css style. We have pull-right to get this button to the right edge of panel.

 Rails |  copy code |? 
1
.panel-body
2
  = f.inputs do
3
    .field
4
      = f.input :email
5
    .remove-link
6
      = link_to_remove_association f, {:class => 'btn-xs btn-default pull-right'} do
7
        %span.glyphicon.glyphicon-remove
8
          Delete

Partial for phone form

Create file:  /opt/sod/app/views/contact_people/_phone_fields.html.haml

 Rails |  copy code |? 
01
= f.inputs do
02
  .field
03
    = f.input :country_code
04
    = f.input :number
05
    = f.input :extension
06
  .remove-link
07
    = link_to_remove_association f, {:class => 'btn-xs btn-default pull-right'} do
08
      %span.glyphicon.glyphicon-remove
09
        Delete
10

Now we can use this partials in contact_person form (app/views/contact_people/_form.html.haml).

Use partials in contact person form

It is a formtastic loop through emails and phones to generate form fields for it. The nice thing is: link_to_add_association which comes from coocon gem. It makes all the magic of adding embeded element for you.

 Rails |  copy code |? 
01
 ........
02
  %h4 Email addresses
03
  = f.semantic_fields_for :email do |email|
04
    = render 'email_fields', f: email
05
  .links
06
    = link_to_add_association 'Add', f, :email
07
  %h4 Telephone numbers
08
  = f.semantic_fields_for :phone do |phone|
09
    = render 'phone_fields', f: phone
10
  .links
11
    = link_to_add_association 'Add', f, :phone
12
  = f.actions do
13
    = f.action :submit, :as => :input

Make UI more fancy

Now we are almost there. But lets use some goods from bootstrap. We will style buttons and add some nice features from  javascript library. Lets hide form fields for phone numbers and just show user only the number.

  1. Use bootstrap grid layout to put emails and phones in two columns.
  2. Add styling to buttons
  3. Use accordion from bootstrap javascript.

The code

 Rails |  copy code |? 
01
  .col-md-6
02
    %h4 Email addresses
03
    .panel.panel-default
04
      = f.semantic_fields_for :email do |email|
05
        = render 'email_fields', f: email
06
      = link_to_add_association 'Dodaj', f, :email, {:class => 'btn-xs btn-default'}
07
  .col-md-6
08
    %h4 Phone numbers
09
    .panel-group{:id => "#accordion"}
10
      .panel.panel-default
11
        = f.semantic_fields_for :phone do |phone|
12
          .panel-heading
13
            .panel-title
14
              %button{"type" => "button", "data-toggle" => "collapse", "data-target" => "#collapse-#{phone.object.id}", "data-parent" => "#accordion", "href" => "#collapseOne"}
15
                %span.glyphicon.glyphicon-zoom-in
16
              %button{"type" => "button", "class" => "btn btn-default"}
17
                = phone.object.country_code + phone.object.number
18
          .panel-collapse.collapse{:id => "collapse-#{phone.object.id}"}
19
            = render 'phone_fields', f: phone
20
      = link_to_add_association 'Dodaj', f, :phone, {:class => 'btn-xs btn-default'}
21
  .col-md-12
22
    .control-group
23
      .controls
24
        = f.actions do
25
          = f.action :submit, :as => :input, button_html: {class: 'btn btn-lg btn-primary'}

Lets brake it into pieces.

  1.   .col-md-6 for emails and   .col-md-6 for phones. In bootstrap grid layout you have to sum into 12 grid elements. So if you have 6+6=12 -> screen divided to two columns. 
  2. .panel.panel-default    using panel from bootstrap -> http://getbootstrap.com/components/#panels
  3. Added button classes to “link_to_add_association”  {:class => ‘btn-xs btn-default’}
  4. For phone numbers I followed documentation from bootstrap http://getbootstrap.com/javascript/#collapse and from stackoverflow http://stackoverflow.com/questions/18639651/bootstrap-collapse-with-haml-and-railsIt is a bunch of panels, but the most tricky part is about calling .panel-collapse.collapse to show up on button click.
  5. The button:
     Rails |  copy code |? 
    1
    %button{"type" => "button", "data-toggle" => "collapse", "data-target" => "#collapse-#{phone.object.id}", "data-parent" => "#accordion", "href" => "#collapseOne"}
    2
                    %span.glyphicon.glyphicon-zoom-in
    Do not use “button_to”, “link_to” or whatever you will think about in HAML. I tried this and it breaks the form.

data-target is the most important thing because it points to panel to show up on click. I am using the phone ID to have unique CSS ID’s. So whatever how much phone numbers will be it will always work. As a dessert we are adding icon to click.

The panel to show up:

 Rails |  copy code |? 
1
.panel-collapse.collapse{:id => "collapse-#{phone.object.id}"}
2
            = render 'phone_fields', f: phone

Now in this panel we are setting CSS id in the same way. Get phone number ID to get the same value as in button generation. So when we click button we will call this panel to show up. In panel we are rendering form fields.

The outcome

Thanks to Piotr Huk for help with partials for embedded objects.

Categories: Ruby on rails Tags:

Table row as link to edit element in Rails.

March 5th, 2014 No comments

table-clickIf you have a list of objects like users as table probably you will want to click on table row to edit this element.

How to make it clickable and redirect it to object edit?

How table should look like?

 Rails |  copy code |? 
1
- @users.each do |user|
2
   %tr{:"data-link" => edit_user_path(user), :id => "datalink"}
3
   %td= user.name
4
   ...
5

This way we will have data attribute attached to

as path to user edit.

Now we need javascript to make it happen.

In your users.js.coffee:

 Javascript |  copy code |? 
1
#This is to enable link to element by table row click
2
#tr have to have element :"data-link" pointing to URL from app and should have
3
# :id => "datalink" for changing mouse pointer by css
4
$ ->
5
   $("tr[data-link]").click ->
6
       window.location.replace($(this).data("link"));

The last thing is to suggest your application user that this raw is clickable. We need to change mouse pointer to be “hand”:

 CSS |  copy code |? 
1
/*Make table row change pointer because it is link */
2
#datalink {
3
   cursor: pointer;
4
}

Categories: Ruby on rails Tags:

The best bootstrap css table style ever

March 3rd, 2014 No comments

If you would like to have the best looking table using bootstrap css library use this styles:

 Rails |  copy code |? 
1
%table.table.table-striped.table-bordered.table-condensed.table-hover

It is in HAML but simply use all this styles at once if you are not using it.

Add tags with application version into your git branch and show it in view

February 25th, 2014 No comments

You can look at “A successful branching model” for very good reference about layout of branches and worfklow on application in git.

According to this you add tags to commits in master branch. How to add tag with version?

1
git tag -a v1.4 -m 'my version 1.4'

Or we can add tag to existing commit by using commit hash:

1
git tag -a v1.2 -m 'version 1.2' 9fceb02

How can I add automatic version number in appliaction footer?

You can read tag from GIT and create global variable in Rails. This way you can use version number in any place. For example in layout.

Following example from http://stackoverflow.com/questions/9073446/where-do-you-store-your-rails-applications-version-number

Edit your application.rb file and place:

 Rails |  copy code |? 
1
if Rails.env.development?
2
  # Update version file from latest git tag
3
  File.open('config/version', 'w') do |file|
4
    file.write `git describe --tags --always` # or equivalent
5
  end
6
end
7
 
8
config.version = File.read('config/version')

Version file will be update every time you start your server – for example Unicorn. It will work only for development environment.

Now you can use this variable in your app view – it may by footer in app/views/layouts/application.html.haml (HAML in my example):

 Rails |  copy code |? 
1
%p.text-right #{MyAPP::Application::config.version}

Categories: Ruby on rails Tags: ,

Bootstrap glyphicons in = link_to haml view

February 8th, 2014 No comments

Problem

How to add glyphicon into button in haml view?

Solution

 Rails |  copy code |? 
1
 = link_to  new_person_path, {:class => 'btn btn-lg btn-default'} do
2
   %span.glyphicon.glyphicon-plus
3
      Add person

Categories: Ruby on rails Tags:

Glyphicons from Bootstrap in Rails 4

February 8th, 2014 No comments

Intro

You have bootstrap css in 

1
app/assets/stylesheets/

 You have fonts from bootstrap in 

1
app/assets/fonts

Now you want to use icons like:

1
<span class="glyphicon glyphicon-cog"></span>

And… it doesn’t work. You see only some strange ractangle instead of icon.

Fix it

Edit your config/application.rb
and in section: class Application < Rails::Application

1
  config.assets.enabled = true
2
  config.assets.paths << "#{Rails.root}/app/assets/fonts"

Now run:

1
rake assets:precompile RAILS_ENV=development

Edit your app/assets/stylesheets/bootstrap.css
and make it like this:

 CSS |  copy code |? 
1
@font-face {
2
font-family: 'Glyphicons Halflings';
3
   src: url('../glyphicons-halflings-regular.eot');
4
   src: url('../glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('/glyphicons-halflings-regular.woff') format('woff'), url('glyphicons-halflings-regular.ttf') format('truetype'), url('/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
5
}

 I don’t know if it is the best way but it works.

Categories: Ruby on rails Tags:

Dwanaście przydatnych wtyczek WordPress

July 12th, 2013 No comments

wordpress-pluginsOto moja lista najbardziej przydatnych wtyczek WordPressowych:

  1. All in one FaviconZamiast grzebać w szablonie aby ustawić małą ikonkę favicon po prostu się to wrzuca poprzez wtyczkę. Gotowe.
  2. bxSlider integration for WordPressJeśli się chce zrobić fajny slider, czyli takie przewijane obrazki na stronie.
  3. cformsIINajlepsza wtyczka do tworzenia formularzy, które potem są przesyłane na maila i jednocześnie zapisywane w bazie na serwerze.
  4. CSS & Javascript ToolboxChcesz zmienić wygląd szablonu nie tworząc child theme? Zmieniasz CSS i umieszczasz javascript na stronie przy pomocy tej wtyczki. Można np. spowodować, że strona zupełnie inaczej wygląda jak się wejdzie na “home” a inaczej na podstronach.
  5. Disable CommentsSkuteczna metoda na wyeliminowanie funkcjonalności komentarzy w Wordpresie. Przydatne gdy WordPress nie jest jako blog tylko jako normalna strona internetowa.
  6. Google Analytics for WordPressŁatwe włączenie statystyk Google Analytics. Fajne jest to, że w ustawieniach zaawansowanych można wyłączyć śledzenie zalogowanych użytkowników. Dzięki temu sami nie generujemy ruchu w statystykach.
  7. Google XML SitemapsGenerator map witryny dla Google.
  8. Link IndicationTaki bajerek. Dodaje do linków ikonkę.
  9. PolylangJeśli chcesz zrobić stronę wielojęzyczną na Wordpresie.
  10. Restrict WidgetsSterowanie tym na jakich stronach mają się pojawić jakie widgety.
  11. UK Cookie ConsentProste rozwiązanie jeśli chodzi o wymóg akceptacji zapisywania plików cookie.
  12. WP Google FontsDzięki temu można w prosty sposób używać bardzo fajnych fontów na stronie.

Export data from firebird database to Excel using PHP

March 18th, 2013 3 comments

If you want to create simple reporting (rather exporting) tool in PHP for use with Firebird database this post is for you. I assume you have Firebird on Windows 7 machine (in Windows 8 it should be similar) with IIS. With some basic changes this will work on Apache in Windows.

First step – create your view in firebird

Take your time to create proper SQL query as new view in database. I think it is more comfortable. In your reporting tool you will just run select * from view_name.

2 step – enable IIS on machine

In Windows run Programs and Features and then click Turn Windows features on or off

Enable World Wide Web services and than enable CGI in Appllication Development Features.

3 step – get PHP

Go to web page http://www.php.net/downloads.php and than “Windows binaries and source”. Download x86 Non Thread Safe ZIP file

Unpack ZIP file and place its content in c:\PHP

Go to c:\PHP and make copy of file php.ini-development     Name this file php.ini

4 step – Configure your environment

  1. Open php.ini file in text editor.
  2. Find ;cgi.force_redirect = 1and change it to:cgi.force_redirect = 0
  3. Find ;error_log = php_errors.logand change it to:error_log = php_errors.logThat way you will be able to find all PHP errors in file c:\PHP\php_errors.log

    Just in case.

  4. Find ;extension=php_interbase.dlland change it to:extension=php_interbase.dllThis will enable support for our database.
  5. Find :extension_dir = “ext” and change it to:extension_dir = “ext”By default ext directory make no effect and also your interbase extension in it.
  6. Go to C:\Program Files (x86)\Firebird\Firebird_1_5\binSelect file fbclient.dll and copy it to C:\PHPCopy fbclient.dll also to c:\windows\system32
  7. Go to C:\PHP\extCopy file: php_interbase.dll to c:\windows\system32
  8. Go to C:\PHPCopy files: libeay32.dll and ssleay32.dll to c:\windows\system32

 6 step – IIS configuration

  1. Run IIS manager (windows key + R    inetmgr)
  2. You can enable PHP for whole server or just one site. Go to Handler Mappings and new module mapping.Request path: *.phpModule: FastCGIModule

    Executable: C:\php\php-cgi.exe

  3. Now go to sites (list of sites).Click on Default Web SiteChoose option “Limits…” on the right menubar.

    Type in 600 seconds. Reports may take long time, so you don’t want timeouts before the end of report generation.

  4. Make shure that IIS is working properly. Type in localhost in your web browser. There should be some default webpage.

7 step – PHP Script for excel file generation

  1. Download recent version of PHPExcel from http://phpexcel.codeplex.com   Extract it and place Classes directory in your Default Web Page directory (C:\inetpub\wwwroot).
  2. Create file export.php and place it in your Default Web Page directory. (C:\inetpub\wwwroot)  Paste my script to it.
  3. Now you need to edit the script. You need path to your database file, username and password. You need to define name for your query. Script will generate excel file if you use this script like http://localhost/export.php?select=contacts it will run query defined in script with that name. This way you can generate files for many different queries using single php file.
  4. If you go to http://localhost/export.php?select=contacts it will create Excel file with name constructed using query name, current date and time like contacts2013-03-18×17:24.xlsx

The script

 PHP |  copy code |? 
01
<?php
02
 
03
/**
04
 * FireExport PHP script 
05
 *
06
 * It is script for generating excel files from firebird database.
07
 * Many thanks to frank1973 (http://phpexcel.codeplex.com/discussions/392942) for posting script for exporting from MySQL.
08
 * It is modification of this script for FireBird.
09
 *
10
 * This library is free software; you can redistribute it and/or
11
 * modify it under the terms of the Creative Commons Attribution 3.0 License. 
12
 * http://creativecommons.org/licenses/by/3.0/
13
 * So if you want to reuse it just inform about my work in it.
14
 *
15
 * This library is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18
 *
19
 * @copyright  Maciej Egermeier  http://www.egermeier.com
20
 * @license    http://creativecommons.org/licenses/by/3.0/
21
 * @version    1.0, 2013-03-18
22
 */
23
 
24
$select=$_GET["select"]; //selected query
25
$date = (date ("Y-m-d")); //today
26
$time = (date ("H-i")); //current time
27
set_time_limit(0); //set time limit - reports may take long time
28
 
29
$host = 'localhost:C:/BAZALEFTHEND/LH_MULTI.GDB';  //!!!!!here you need to specify your database path.
30
$username='SYSDBA';   //!!!!!username for database
31
$password='masterkey';   //!!!!!password for database user
32
 
33
//!!!! change this
34
//It will wirk if you run this script like this:  http://localhost/export.php?select=adresy
35
if ($select=="adresy"){ //checking if specific query is needed and change query text
36
 $stmt="Select * from MAC_ADRESY"; //here you need to define your query to database. It can be also view.
37
}
38
 
39
//if you need another query
40
//If you run your script like this: http://localhost/export.php?select=contacts it will run your query
41
//uncomment this:
42
//
43
//if ($select=="contacts"){
44
// $stmt="Select * from contacts"; //here you need to define your query to database
45
//}
46
 
47
 
48
/** require the PHPExcel file 1.0 */
49
    require 'Classes/PHPExcel.php';
50
 
51
/** Set Memory Limit 1.0 */
52
    ini_set("memory_limit","500M"); // set your memory limit in the case of memory problem
53
 
54
/** Caching to discISAM 1.0*/
55
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_discISAM;
56
$cacheSettings = array( 'dir'  => '/usr/local/tmp' // If you have a large file you can cache it optional
57
                      );
58
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
59
 
60
/** connection with the database 1.0 */
61
 
62
//here is connection to your Firebird database.
63
$dbh = ibase_connect ( $host, $username, $password ) or die ("error in db connect");
64
$query = ibase_prepare($stmt);
65
$result=ibase_execute($query);
66
 
67
 
68
/** Create a new PHPExcel object 1.0 */
69
   $objPHPExcel = new PHPExcel();
70
   $objPHPExcel->getActiveSheet()->setTitle('Data');
71
 
72
 
73
/** Loop through the result set 1.0 */
74
    $rowNumber = 1; //start in cell 1
75
    while ($row = ibase_fetch_row($result)) {
76
       $col = 'A'; // start at column A
77
       foreach($row as $cell) {
78
          $objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
79
          $col++;
80
       }
81
       $rowNumber++;
82
}
83
 
84
/** Create Excel 2007 file with writer 1.0 */
85
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
86
    header('Content-Disposition: attachment;filename="'.$select.$date."x".$time.'.xlsx"'); //using query name, current date and time as file name
87
    header('Cache-Control: max-age=0');
88
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
89
    $objWriter->save('php://output');
90
exit;
91
 
92
?>

Categories: Uncategorized Tags:

Koniec bezpłatnego google apps.

December 7th, 2012 No comments

No i stało się. Google apps już nie jest za darmo. Ci którzy załapali się na bezpłatną wersję, nadal będą mogli jej używać. Reszta musi płacić 50$ za użytkownika rocznie.

~150 zł to nie jest koszt, który chciałbym ponieść prowadząc skrzynki swojej rodziny we własnej domenie. Czyli “focus on business customer”…

Spoglądając od strony małej polskiej firmy: “150zł za użytkownika.. za co? Przecież mi wystarczy darmowa skrzynka razem z hostingiem strony firmowej”. A gdyby tak współdzielić kalendarze? Dzielenie się plikami z ludźmi poza firmą? Ale nie wiem, czy tę różnicę jest łatwo “sprzedać”.


 

Wdrożenia Google Apps