RoR Step By Step

本文介绍了如何安装 Ruby 和 Rails,通过示例演示了如何创建并运行一个简单的 Rails Web 应用程序,包括安装步骤、环境配置、模块介绍及开发流程。

 


 

1、安装Ruby

 http://rubyforge.org/ 下载 One-Click Installer

最新版1.8.6

2、测试是否安装成功
建议一个Test.rb文件,内容如下

  1. hello = "Hello Ruby World."
  2. puts hello  

在命令行下运行 ruby Test.rb ,注意安装时%RUBY_HOME%/bin已经设置在你的PATH中了,检查一下即可,运行正确的话就会显示
Hello Ruby World.
结果出来

 

3、利用gem安装其它模块
在命令行下运行 gem install rails
安装提示与结果
Install required dependency activesupport? [Yn]  y
Install required dependency activerecord? [Yn]  y
Install required dependency actionpack? [Yn]  y
Install required dependency actionmailer? [Yn]  y
Install required dependency actionwebservice? [Yn]  y
Successfully installed rails-1.1.6
Successfully installed activesupport-1.3.1
Successfully installed activerecord-1.14.4
Successfully installed actionpack-1.12.5
Successfully installed actionmailer-1.2.5
Successfully installed actionwebservice-1.1.6
Installing ri documentation for activesupport-1.3.1...
Installing ri documentation for activerecord-1.14.4...
Installing ri documentation for actionpack-1.12.5...
Installing ri documentation for actionmailer-1.2.5...
Installing ri documentation for actionwebservice-1.1.6...
Installing RDoc documentation for activesupport-1.3.1...
Installing RDoc documentation for activerecord-1.14.4...
Installing RDoc documentation for actionpack-1.12.5...
Installing RDoc documentation for actionmailer-1.2.5...
Installing RDoc documentation for actionwebservice-1.1.6...

再运行gem list检查一下看是否安装上去了,会有一堆列表显示,新的也在里面,安装前后各gem list一下,就可以对比得到以下结果

4、安装后各模块介绍
actionmailer (1.2.5) 邮件分发与测试模块,类似Java里的JavaMail的东东
actionpack (1.12.5) 类似于Web的MVC中的V与C
actionwebservice (1.1.6) Web Service支持
activerecord (1.14.4) ORM工具,类似Java中的Hibernate之类的
activesupport (1.3.1) Rails框架所依赖的一些基础工具类
rails (1.1.6) Web应用框架Rails包含模板引擎,控制层及ORM

5、默认安装后的模块有
fxri (0.3.3)
    Graphical interface to the RI documentation, with search engine.
fxruby (1.6.1, 1.2.6)
    FXRuby is the Ruby binding to the FOX GUI toolkit.
log4r (1.0.5) 日志库,Java中就象Log4J或Jakarta的Commons-Logging
rake (0.7.1) 类似make的工具,Java中就象Ant或Maven
sources (0.0.1)
    This package provides download sources for remote gem installation
win32-clipboard (0.4.0)
    A package for interacting with the Windows clipboard
win32-dir (0.3.0)
    Extra constants and methods for the Dir class on Windows.
win32-eventlog (0.4.1)
    Interface for the MS Windows Event Log.
win32-file (0.5.2)
    Extra or redefined methods for the File class on Windows.
win32-file-stat (1.2.2)
    A File::Stat class tailored to MS Windows
win32-process (0.4.2)
    Adds fork, wait, wait2, waitpid, waitpid2 and a special kill method
win32-sapi (0.1.3)
    An interface to the MS SAPI (Sound API) library.
win32-sound (0.4.0)
    A package for playing with sound on Windows.
windows-pr (0.5.1)
    Windows functions and constants predefined via Win32API

6、创建Web应用
在命令行下运行 rails rorweb ,会在rorweb目录下创建相应的一堆完整的Web应用的目录结构,然后你应该做的就是写你的程序了。
      create
      create  app/controllers
      create  app/helpers
      create  app/models
      create  app/views/layouts
      create  config/environments
      create  components
      create  db
      create  doc
      create  lib
      create  lib/tasks
      create  log
      create  public/images
      create  public/javascripts
      create  public/stylesheets
      create  script/performance
      create  script/process
      create  test/fixtures
      create  test/functional
      create  test/integration
      create  test/mocks/development
      create  test/mocks/test
      create  test/unit
      create  vendor
      create  vendor/plugins
      create  tmp/sessions
      create  tmp/sockets
      create  tmp/cache
      create  Rakefile
      create  README
      create  app/controllers/application.rb
      create  app/helpers/application_helper.rb
      create  test/test_helper.rb
      create  config/database.yml
      create  config/routes.rb
      create  public/.htaccess
      create  config/boot.rb
      create  config/environment.rb
      create  config/environments/production.rb
      create  config/environments/development.rb
      create  config/environments/test.rb
      create  script/about
      create  script/breakpointer
      create  script/console
      create  script/destroy
      create  script/generate
      create  script/performance/benchmarker
      create  script/performance/profiler
      create  script/process/reaper
      create  script/process/spawner
      create  script/runner
      create  script/server
      create  script/plugin
      create  public/dispatch.rb
      create  public/dispatch.cgi
      create  public/dispatch.fcgi
      create  public/404.html
      create  public/500.html
      create  public/index.html
      create  public/favicon.ico
      create  public/robots.txt
      create  public/images/rails.png
      create  public/javascripts/prototype.js
      create  public/javascripts/effects.js
      create  public/javascripts/dragdrop.js
      create  public/javascripts/controls.js
      create  public/javascripts/application.js
      create  doc/README_FOR_APP
      create  log/server.log
      create  log/production.log
      create  log/development.log
      create  log/test.log

7、启动Web应用
进入rorweb目录,运行 ruby script/server 启动之,信息如下
=> Booting WEBrick...
=> Rails application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with --help for options
[2006-11-25 08:47:44] INFO  WEBrick 1.3.1
[2006-11-25 08:47:44] INFO  ruby 1.8.4 (2006-04-14) [i386-mswin32]
[2006-11-25 08:47:44] INFO  WEBrick::HTTPServer#start: pid=2564 port=3000

默认webrick服务器启用了3000端口,访问一下 http://localhost:3000 ,打开后可以看到如下之类的信息。
Welcome aboard
You’re riding the Rails!
About your application’s environment
点击查看:
Ruby version 1.8.4 (i386-mswin32)
RubyGems version 0.9.0
Rails version 1.1.6
Active Record version 1.14.4
Action Pack version 1.12.5
Action Web Service version 1.1.6
Action Mailer version 1.2.5
Active Support version 1.3.1
Application root X:/OpenSource/Ruby/rorweb
Environment development
Database adapter mysql

关于webrick服务器更多的信息可以访问 http://www.webrick.org/

8、写一个HelloRoR的Web程序
打开rorweb/app目录,可以看到四个子目录
controllers
helpers
models

del.icio.us 标记: Ruby on Rails


views
一看就知道是什么作用了吧:)

仍在rorweb目录,运行 ruby script/generate controller HelloRoR 可以看到如下的创建信息
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/hello_ro_r
      exists  test/functional/
      create  app/controllers/hello_ro_r_controller.rb
      create  test/functional/hello_ro_r_controller_test.rb
      create  app/helpers/hello_ro_r_helper.rb

创建一个app/views/hello_ro_r目录及三个文件

打开 hello_ro_r_controller.rb 进行编辑,增加内容后全部如下:

ruby 代码 

  1. class HelloRoRController < ApplicationController   
  2. def index   
  3.   render_text "Hello RoR World"
  4. end
  5. def rails   
  6.   render_text "Hello Rails"
  7. end
  8. end

访问 http://localhost:3000/hello_ro_r/ 就可以看到Hello RoR World结果了
访问 http://localhost:3000/hello_ro_r/rails 就可以看到Hello Rails结果了

注意是 hello_ro_r 不是HelloRoR,默认是小写,并写大小写之间用_分隔了,要注意一下,如果要进行对应,就全部小写建立应用,如:
运行 ruby script/generate controller helloror ,这样就是生成 helloror_controller.rb 了,然后访问 http://localhost:3000/helloror/

其它:1.8.4与1.8.5的区别
1.8.4
win32-clipboard (0.4.0)
win32-eventlog (0.4.1)
win32-process (0.4.2)
windows-pr (0.5.1)
1.8.5
win32-clipboard (0.4.1)
win32-eventlog (0.4.2)
win32-process (0.5.1)
windows-pr (0.5.3, 0.5.1)

1.8.5的升级:gem install rails
Bulk updating Gem source index for: http://gems.rubyforge.org
Install required dependency activesupport? [Yn]  y
Install required dependency activerecord? [Yn]  y
Install required dependency actionpack? [Yn]  y
Install required dependency actionmailer? [Yn]  y
Install required dependency actionwebservice? [Yn]  y
Successfully installed rails-1.1.6
Successfully installed activesupport-1.3.1
Successfully installed activerecord-1.14.4
Successfully installed actionpack-1.12.5
Successfully installed actionmailer-1.2.5
Successfully installed actionwebservice-1.1.6
Installing ri documentation for activesupport-1.3.1...
While generating documentation for activesupport-1.3.1
... MESSAGE:   Unhandled special: Special: type=17, text="<!-- HI -->"
... RDOC args: --ri --op F:/OpenSource/RoR/Ruby/lib/ruby/gems/1.8/doc/activesupport-1.3.1/ri --quiet lib
(continuing with the rest of the installation)
Installing ri documentation for activerecord-1.14.4...
Installing ri documentation for actionpack-1.12.5...
While generating documentation for actionpack-1.12.5
... MESSAGE:   Unhandled special: Special: type=17, text="<!-- The header part of this layout -->"
... RDOC args: --ri --op F:/OpenSource/RoR/Ruby/lib/ruby/gems/1.8/doc/actionpack-1.12.5/ri --quiet lib
(continuing with the rest of the installation)
Installing ri documentation for actionmailer-1.2.5...
Installing ri documentation for actionwebservice-1.1.6...
Installing RDoc documentation for activesupport-1.3.1...
Installing RDoc documentation for activerecord-1.14.4...
Installing RDoc documentation for actionpack-1.12.5...
Installing RDoc documentation for actionmailer-1.2.5...
Installing RDoc documentation for actionwebservice-1.1.6...

 

 


"D:\Program Files\Python39\python.exe" C:\Users\E918928\PycharmProjects\pythonProject\LZRR\代码1、\能管检查\测试1105.py 📘 脚本开始运行,日志记录至: D:\Class\能管比对\导出文件\run_log_20251110_112034.txt 已删除: 42.水系统-生产用水-纯水总耗用量(FAB1).xlsx 已删除: 43.水处理系统(旧)-生产用水-LSW总耗用量(FAB1).xlsx 已删除: 44.水系统-自来水用量.xlsx 已删除: 45.水系统-纯水曲线看板-原水泵出口流量计(P1-1).xlsx 已删除: 46.水系统-纯水曲线看板-原水泵出口流量计(P1-3).xlsx 已删除: 列表 (1).xlsx 已删除: 列表.xlsx 共清理 7 个旧文件 正在访问登录页... 输入用户名和密码... 等待登录完成... 加载操作集: OPERATIONS_0 (1 项) 加载操作集: OPERATIONS_2 (33 项) 共发现 34 个任务 1. 0.预操作 2. 42.水系统-生产用水-纯水总耗用量(FAB1) 3. 43.水处理系统(旧)-生产用水-LSW总耗用量(FAB1) 4. 44.水系统-自来水用量 5. 45.水系统-纯水曲线看板-原水泵出口流量计(P1-1) 6. 46.水系统-纯水曲线看板-原水泵出口流量计(P1-3) 7. 47.水系统-纯水曲线看板-MAU/PCW水泵出口流量计(P1-1) 8. 48.水系统-纯水曲线看板-MAU/PCW水泵出口流量计(P1-3) 9. 49.水系统-纯水曲线看板-软水泵出口流量计 10. 50.水系统-纯水曲线看板--LSR收集水量(P1-3) 11. 51.水系统-纯水曲线看板--LSR产水量(P1-1) 12. 52.水系统-纯水曲线看板--LSR产水量(P1-3) 13. 53.水系统-纯水曲线看板-ROR补LSW水量 14. 54.水系统-纯水曲线看板-DIR产水至过滤水池(P1-1) 15. 55.水系统-纯水曲线看板-DIR产水至过滤水池(P1-3) 16. 56.水系统-纯水曲线看板-DIR传输泵出口流量计(P1-1) 17. 57.水系统-纯水曲线看板-DIR传输泵出口流量计(P1-3) 18. 58.水系统-纯水曲线看板--DIR回收率(P1-1) 19. 59.水系统-纯水曲线看板-DIR回收率(P1-3) 20. 60.水系统-纯水曲线看板-Reuse Water水量 21. 61.水系统-纯水曲线看板-Soft Water用量 22. 62.水系统-纯水曲线看板-1st DI耗用量 23. 63.水系统-纯水曲线看板-Central scrubber用量 24. 64.水系统-纯水曲线看板-CCoolingTower用水量(中水+自来水) 25. 65.水系统-UPW_ECF 26. 66.水系统-纯水电盘电量-纯水用电量(P1-1) 27. 67.水系统-纯水电盘电量-纯水用电量(P1-3) 28. 68.水系统-WWT曲线看板-WWT各系统水量 29. 69.水系统-WWT曲线看板-WWT放流水_pH 30. 70.水系统-WWT曲线看板-WWT放流水质_F&NH3_N 31. 71.水系统-纯水电盘电量-WWT放流水质_COD&SS 32. 72.水系统-纯水电盘电量-WWT放流水质_Cu 33. 73.水系统-WWT产量 34. 74.水系统-WWT_ECF 执行任务: 0.预操作 预操作完成 执行任务: 42.水系统-生产用水-纯水总耗用量(FAB1) 点击: 水系统 点击: 生产用水 点击: 纯水总耗用量(FAB1) 点击: 查询 点击: 导出 ✅ 导出完成: 42.水系统-生产用水-纯水总耗用量(FAB1).xlsx 执行任务: 43.水处理系统(旧)-生产用水-LSW总耗用量(FAB1) 点击: LSW总耗用量(FAB1) 点击: 查询 点击: 导出 ✅ 导出完成: 43.水处理系统(旧)-生产用水-LSW总耗用量(FAB1).xlsx 执行任务: 44.水系统-自来水用量 点击: 能源种类 点击: 自来水用量 点击: 查询 点击: 导出 ✅ 导出完成: 44.水系统-自来水用量.xlsx 执行任务: 45.水系统-纯水曲线看板-原水泵出口流量计(P1-1) 点击: 纯水曲线看板 点击: 原水泵出口流量计(P1-1) 点击: 查询 点击: 导出 ✅ 导出完成: 45.水系统-纯水曲线看板-原水泵出口流量计(P1-1).xlsx 执行任务: 46.水系统-纯水曲线看板-原水泵出口流量计(P1-3) 点击: 原水泵出口流量计(P1-3) 点击: 查询 点击: 导出 ✅ 导出完成: 46.水系统-纯水曲线看板-原水泵出口流量计(P1-3).xlsx 执行任务: 47.水系统-纯水曲线看板-MAU/PCW水泵出口流量计(P1-1) 点击: MAU/PCW水泵出口流量计(P1-1) 点击: 查询 点击: 导出 🚨 发生未预期错误: [WinError 3] 系统找不到指定的路径。: 'D:\\Class\\能管比对\\导出文件\\列表.xlsx' -> 'D:\\Class\\能管比对\\导出文件\\47.水系统-纯水曲线看板-MAU/PCW水泵出口流量计(P1-1).xlsx' 🚪 浏览器已关闭 🔚 脚本运行结束 Process finished with exit code 0 —— from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time import os import glob import sys from datetime import datetime # 在文件顶部或其他地方加几行(不会被执行也没关系) import menu_operations0 import menu_operations1 import menu_operations2 import menu_operations3 import menu_operations4 # ==================== 日志重定向类 ==================== class TeeLogger: def __init__(self, filename): self.terminal = sys.stdout self.log = open(filename, "w", encoding="utf-8") def write(self, message): self.terminal.write(message) self.log.write(message) self.log.flush() # 立即写入文件 def flush(self): self.terminal.flush() self.log.flush() def clear_download_dir(download_dir): """清空指定目录中的旧文件""" if not os.path.exists(download_dir): os.makedirs(download_dir) print(f"创建目录: {download_dir}") patterns = ["*.xlsx", "*.xls", "*.csv", "*.pdf"] deleted_count = 0 for pattern in patterns: for file_path in glob.glob(os.path.join(download_dir, pattern)): try: os.remove(file_path) print(f"已删除: {os.path.basename(file_path)}") deleted_count += 1 except Exception as e: print(f"删除失败: {os.path.basename(file_path)}, 错误: {e}") if deleted_count == 0: print("下载目录为空") else: print(f"共清理 {deleted_count} 个旧文件") def load_operations_from_module(module_name): """从模块加载所有 OPERATIONS_* 字典并合并""" try: module = __import__(module_name) operations = {} for attr in dir(module): if attr.startswith("OPERATIONS_"): obj = getattr(module, attr) if isinstance(obj, dict): operations.update(obj) print(f"加载操作集: {attr} ({len(obj)} 项)") return operations except Exception as e: print(f"导入模块 {module_name} 失败: {e}") return {} # ==================== 主程序 ==================== if __name__ == "__main__": # --- 配置区 --- download_dir = r"D:\Class\能管比对\导出文件" login_url = "http://10.11.20.117:7001/energy4/#/login" username = "E915285" password = "123456" # --- 创建日志文件 --- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") log_filename = f"run_log_{timestamp}.txt" log_filepath = os.path.join(download_dir, log_filename) # 重定向 stdout 到终端 + 日志文件 sys.stdout = TeeLogger(log_filepath) print(f"📘 脚本开始运行,日志记录至: {log_filepath}") driver = None # 防止 finally 出错 try: # 1. 清理旧文件 clear_download_dir(download_dir) # 2. 配置并启动浏览器 options = webdriver.ChromeOptions() options.add_argument("--headless=new") # 可注释掉查看页面 options.add_argument("--window-size=1920,1080") options.add_argument("--disable-gpu") options.add_argument("--no-sandbox") options.add_experimental_option("useAutomationExtension", False) options.add_experimental_option("excludeSwitches", ["enable-automation"]) prefs = { "download.default_directory": download_dir, "download.prompt_for_download": False, "safebrowsing.enabled": True, } options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(options=options) driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => false});") # 3. 登录系统 print("正在访问登录页...") driver.get(login_url) WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='text']"))) print("输入用户名和密码...") driver.find_element(By.CSS_SELECTOR, "input[type='text']").send_keys(username) driver.find_element(By.CSS_SELECTOR, "input[type='password']").send_keys(password) driver.find_element(By.CSS_SELECTOR, "button.loginBtn").click() print("等待登录完成...") WebDriverWait(driver, 20).until(EC.url_contains("/energy4/#/")) # 4. 加载所有操作流程 all_operations = {} for mod in [ "menu_operations0", # "menu_operations1", "menu_operations2", # "menu_operations3", # "menu_operations4", # "menu_operations5", ]: ops = load_operations_from_module(mod) all_operations.update(ops) print(f"\n共发现 {len(all_operations)} 个任务") for i, key in enumerate(all_operations.keys(), 1): print(f"{i}. {key}") # 5. 依次执行每个任务 success_count = 0 wait = WebDriverWait(driver, 10) for task_key, steps in all_operations.items(): print(f"\n执行任务: {task_key}") if task_key == "0.预操作": for step in steps: locator = (By.XPATH, step["xpath"]) wait.until(EC.element_to_be_clickable(locator)).click() time.sleep(1) print("预操作完成") continue # for step in steps: # try: # locator = (By.XPATH, step["xpath"]) # element = wait.until(EC.element_to_be_clickable(locator)) # element.click() # print(f"点击: {step['desc']}") # # # === 特殊处理:如果该步骤需要等待 loading 消失 === # if step.get("wait_for") == "loading": # print("⏳ 等待加载遮罩消失...") # WebDriverWait(driver, 15).until_not( # EC.presence_of_element_located((By.CLASS_NAME, "el-loading-mask")) # ) # print("✅ 加载完成,继续操作") # # time.sleep(1) # 基础防抖 # # except Exception as e: # print(f"❌ 点击失败 [{step['desc']}]: {e}") # break for step in steps: try: locator = (By.XPATH, step["xpath"]) element = wait.until(EC.element_to_be_clickable(locator)) element.click() print(f"点击: {step['desc']}") time.sleep(1) # 等待响应 except Exception as e: print(f"❌ 点击失败 [{step['desc']}]: {e}") continue else: # 仅当 for 成功完成才进入 start_time = time.time() while time.time() - start_time < 30: files = [f for f in glob.glob(f"{download_dir}/*.xlsx") if not os.path.basename(f).startswith("~$")] if files: latest_file = max(files, key=os.path.getmtime) size1 = os.path.getsize(latest_file) time.sleep(1) size2 = os.path.getsize(latest_file) if size1 == size2: # 文件大小稳定,说明下载完成 new_path = os.path.join(download_dir, f"{task_key}.xlsx") counter = 1 base = new_path[:-5] while os.path.exists(new_path): new_path = f"{base}_{counter}.xlsx" counter += 1 os.rename(latest_file, new_path) print(f"✅ 导出完成: {os.path.basename(new_path)}") success_count += 1 break continue # for 循环正常结束 # 如果上面有异常跳出,则走到这里表示失败 print(f"❌ 任务失败: {task_key}") print(f"\n🎉 执行完毕,成功 {success_count}/{len(all_operations)} 个任务") except Exception as e: print(f"🚨 发生未预期错误: {e}") finally: if driver: driver.quit() print("🚪 浏览器已关闭") print("🔚 脚本运行结束") ——出现错误程序继续,不要终止,应该修改主代码哪个地方
11-11
本项目采用C++编程语言结合ROS框架构建了完整的双机械臂控制系统,实现了Gazebo仿真环境下的协同运动模拟,并完成了两台实体UR10工业机器人的联动控制。该毕业设计在答辩环节获得98分的优异成绩,所有程序代码均通过系统性调试验证,保证可直接部署运行。 系统架构包含三个核心模块:基于ROS通信架构的双臂协调控制器、Gazebo物理引擎下的动力学仿真环境、以及真实UR10机器人的硬件接口层。在仿真验证阶段,开发了双臂碰撞检测算法和轨迹规划模块,通过ROS控制包实现了末端执行器的同步轨迹跟踪。硬件集成方面,建立了基于TCP/IP协议的实时通信链路,解决了双机数据同步和运动指令分发等关键技术问题。 本资源适用于自动化、机械电子、人工智能等专业方向的课程实践,可作为高年级课程设计、毕业课题的重要参考案例。系统采用模块化设计理念,控制核心与硬件接口分离架构便于功能扩展,具备工程实践能力的学习者可在现有框架基础上进行二次开发,例如集成视觉感知模块或优化运动规划算法。 项目文档详细记录了环境配置流程、参数调试方法和实验验证数据,特别说明了双机协同作业时的时序同步解决方案。所有功能模块均提供完整的API接口说明,便于使用者快速理解系统架构并进行定制化修改。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值